3ms Java solution


  • 0
        public int[] intersect(int[] nums1, int[] nums2) {
            List<Integer> rtn = new ArrayList<>();
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            for (int i=0, j=0; i<nums1.length && j<nums2.length;) {
                if (nums1[i] == nums2[j]) {
                    rtn.add(nums1[i]);
                    ++j;
                    ++i;
                } else if (nums1[i] < nums2[j]) {
                    ++i;
                } else {
                    ++j;
                }
            }
            return toList(rtn);
        }
        
        private int[] toList(List<Integer> list) {
            int[] rtn = new int[list.size()];
            for (int i=0; i<list.size(); ++i) {
                rtn[i] = list.get(i);
            }
            return rtn;
        }
    

Log in to reply
 

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