Java using Arrays.binarysearch() w/ explanation (6ms)


  • 0

    Arrays.binarySearch(sorted_arr, key) is the simplest and most efficient method to find an element in a sorted array in Java. So, sorting one of the input array(nums1) and iterating the other one(nums2[i]) to find if nums1 contains the same element in nums2.
    Note that the return value will be >= 0 iff. the key is found.

    class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Set<Integer> set = new HashSet<>();  
            Arrays.sort(nums1);
            for(int num : nums2){
                int index = Arrays.binarySearch(nums1, num);
                if(index >=0) set.add(num); }
            
            int[] res = new int[set.size()];
            int i = 0;
            for(int num : set) res[i++] = num;
            return res;
        }
    }
    

Log in to reply
 

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