JAVA - not efficient, but nice and clean


  • 0
    W
     public int[] intersection(int[] nums1, int[] nums2) {
            
            ArrayList<Integer> listNums1 = new ArrayList<>();
    		ArrayList<Integer> listNums2 = new ArrayList<>();
    		for (int i : nums1)
    		{
    			listNums1.add(Integer.valueOf(i));
    		}
    		for (int i : nums2)
    		{
    			listNums2.add(Integer.valueOf(i));
    		}
    		
    		Set<Integer> intersect = (Set) listNums1.stream().filter(listNums2::contains).collect(Collectors.toSet());
    		int  [] result = new int[ intersect.size()]  ;
    		int i=0;
    		for (int oneNumber : intersect)
    		{
    			result[i++] = oneNumber;
    		}
    		
    		return result;
            
        }

  • 0
    C
    import java.util.Arrays;
    
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int length = 0;
            int number =0;
            if ((nums1.length != 0) && (nums2.length != 0)) {
                for (int i = 0; i < nums1.length; i++) {
                    boolean valid = true;
                    if ((i != 0) && (nums1[i-1] == nums1[i])) {
                        valid = false;
                    }
                    if (binarySearch(nums2, nums1[i], 0, nums2.length-1) && valid) {
                        length++;
                    }
                }
            }
            int[] nums3 = new int[length];
            if ((nums1.length != 0) && (nums2.length != 0)) {
                for (int i = 0; i < nums1.length; i++) {
                    boolean valid = true;
                    if ((i != 0) && (nums1[i-1] == nums1[i])) {
                       valid = false;
                    }
                    if (binarySearch(nums2, nums1[i], 0, nums2.length-1) && valid) {
                        nums3[number] = nums1[i];
                        number++;
                    }
                }
            }
            return nums3;
        }
        public static boolean binarySearch(int[] sortedArr, int target, int start, int end) {
    
            if (start > end - 1 && (sortedArr[(start+end)/2] != target)) {
                return false;
            }
            if (sortedArr[(start+end)/2] == target) {
                return true;
            }
            else if (sortedArr[(start+end)/2] < target) {
                start = (start+end)/2 + 1;
            }
            else {
                end = (start+end)/2 - 1;
            }
            return binarySearch(sortedArr, target, start, end);
        }
    }

Log in to reply
 

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