My C++ using unordered_set in 9ms/better, and my Java using hash_set in 5ms

  • 0

    C++ using unorder_set...I used set first, It was run in 18ms and with unordered_set that code can run in 9ms. Sometimes can be 6ms...

    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> hs(nums1.begin(), nums1.end());
        vector<int> storage;
        for(auto item: nums2){
            auto search = hs.find(item);
            if(search != hs.end()){
        return storage;

    Java using HashSet with ArrayList in 5ms

    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> m1 = new HashSet<>();
        ArrayList<Integer> list = new ArrayList<>();
        for(int i=0; i<nums1.length; i++)
        for(int i=0; i<nums2.length; i++){
    	int[] n = new int[list.size()];
    	for(int i=0; i<list.size(); i++)
    		n[i] = list.get(i); //if using .intValue() will add more time on the proformance
        return n;

    If there has better suggestion, I would love to hear from you guys... : )

Log in to reply

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