Java solution with one hashset


  • 0
    P

    public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
    HashSet<Integer> hs = new HashSet<Integer>();
    for(int i = 0; i < nums1.length; i++){
    hs.add(nums1[i]);
    }
    List<Integer> res = new ArrayList<Integer>();
    for(int j = 0; j < nums2.length; j++){
    if(hs.contains(nums2[j])){
    res.add(nums2[j]);
    hs.remove(nums2[j]);
    }
    }
    int[] res_array = new int[res.size()];
    for(int i = 0; i < res.size(); i++){
    res_array[i] = res.get(i);
    }
    return res_array;
    }
    }


  • 0
    K

    please change the code syntax


Log in to reply
 

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