Using hashtable as counter, O(Max(m, n)) Solution.


  • 0
    P
    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            List<Integer> list = new ArrayList<>();
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums1.length; i++) {
                if (map.containsKey(nums1[i])) {
                    int time = map.get(nums1[i]);
                    map.put(nums1[i], time+1);
                } else map.put(nums1[i], 1);
            }
            
            for (int i = 0; i < nums2.length; i++) {
                if (map.containsKey(nums2[i])) {
                    if (map.get(nums2[i]) != 0) {
                        list.add(nums2[i]);
                        int time = map.get(nums2[i]);
                        map.put(nums2[i], time-1);
                    }
                }
            }
            final int size = list.size();
            int[] res = new int[size];
            for (int i = 0; i < size; i++) {
                res[i] = list.get(i);
            }
            return res;
        }
    }
    

Log in to reply
 

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