My O(nlog(n)) java solution.4ms


  • 2
    F
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            if(nums1.length==0||nums2.length==0)
                return new int[0];
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int p1=0;
            int p2=0;
            List<Integer> res=new ArrayList<Integer>();
            while(p1<nums1.length && p2<nums2.length){
                if(nums1[p1]==nums2[p2]){
                    res.add(nums1[p1]);
                    p1++;
                    p2++;
                }
                else if(nums1[p1]<nums2[p2])
                    p1++;
                else 
                    p2++;
            }
            int[] t=new int[res.size()];
            for(int i=0;i<res.size();i++)
                t[i]=res.get(i);
                
            return t;
        }
    }

  • 0
    I

    I wonder where is the part of code that you used to delete the duplicates?


  • 0
    F

    if the duplicates exisits both in nums1 and nums2,the result will contains the duplicates for the smaller times.p1 and p2 will control this.


  • 0
    C

    @futurehau O(nlogn) is gotten via java's Array.sort() method


Log in to reply
 

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