4ms easy Java solution


  • 0
    I
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
    		List<Integer> list = new ArrayList<>();
    		Arrays.sort(nums1);
    		Arrays.sort(nums2);
    		int i = 0, j = 0;
    		while (i < nums1.length && j < nums2.length) {
    			while (nums1[i] != nums2[j]) {
    				if (nums1[i] < nums2[j])
    					i++;
    				else if (nums1[i] > nums2[j])
    					j++;
    				if (j == nums2.length) {
    					j--;
    					break;
    				}
    				if (i == nums1.length) {
    					i--;
    					break;
    				}
    			}
    			if (nums1[i] == nums2[j]) {
    				list.add(nums1[i]);
    				i++;
    				j++;
    			} else if (nums1[i] < nums2[j])
    				i++;
    			else if (nums1[i] > nums2[j])
    				j++;
    		}
    		int[] a = new int[list.size()];
    		for (int k = 0; k < list.size(); k++) {
    			a[k] = list.get(k);
    		}
    		return a;
    	}
    }
    

Log in to reply
 

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