7ms java solution by using two pointers


  • 0
    L

    public class Solution {

    public int[] intersect(int[] nums1, int[] nums2) {

    	Arrays.sort(nums1);
    	Arrays.sort(nums2);
    	ArrayList<Integer> list = new ArrayList<Integer>();
    	int i = 0;
    	int j = 0;
    	int[] result={};
    	if(nums1.length==0||nums2.length==0)
    		return result;
    	while (true) {
    		if (nums1[i] > nums2[j]) {
    			if (j < nums2.length-1)
    				j++;
    			else
    				break;
    		} else if (nums1[i] == nums2[j]){
    			list.add(nums1[i]);
    			if(i<nums1.length-1)
    				i++;
    			else
    				break;
    			if(j<nums2.length-1)
    				j++;
    			else
    				break;
    		}
    		else {
    			if (i < nums1.length-1)
    				i++;
    			else
    				break;
    		}
    	}
    	Iterator<Integer> iter=list.iterator();
    	result=new int[list.size()];
    	int count=0;
    	while(iter.hasNext()){
    		result[count]=iter.next();
    		count++;
    	}
    	return result;
    }
    

    }


Log in to reply
 

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