A Beginner's javascript solution


  • 0

    beat 70% of javascript, the code may looks bad, please leave comment and help me improve.

    var intersect = function(nums1, nums2) {
        var result = [];
        var hash1 = {};
        var hash2 = {};
        var count = 0;
        for (var i = 0, max = nums1.length; i < max; i++) {
            if (!hash1[nums1[i]]) {
                hash1[nums1[i]] = 0;
            }
            hash1[nums1[i]]++;
            if (nums1[i] > count) {
                count = nums1[i];
            }
        }
        for (var i = 0, max = nums2.length; i < max; i++) {
            if (!hash2[nums2[i]]) {
                hash2[nums2[i]] = 0;
            }
            hash2[nums2[i]]++;
        }
        for (var i = 0, max = count + 1; i < max; i++) {
            var low;
            if (hash1[i] && hash2[i]) {
                if (hash1[i] <= hash2[i]) {
                    low = hash1[i];
                } else {
                    low = hash2[i];
                }
                for (var j = 0; j < low; j++) {
                    result.push(i);
                }
            }
        }
        return result;
    };
    

  • 0
    L
    This post is deleted!

  • 0
    L

    @Wang-Cankun

    var intersect = function(nums1, nums2) {
        var result = [];
        var hash1 = {};
        var hash2 = {};
        var count1 = 0;
        var count2 = 0;
        for (var i = 0, max = nums1.length; i < max; i++) {
            if (!hash1[nums1[i]]) {
                hash1[nums1[i]] = 0;
                count1++;
            }
            hash1[nums1[i]]++;
        }
        for (var y = 0, max = nums2.length; y < max; y++) {
            if (!hash2[nums2[y]]) {
                hash2[nums2[y]] = 0;
                count2++;
            }
            hash2[nums2[y]]++;
        }
        var temp;
        if (count1 < count2) {
            temp = hash1;
        } else {
            temp = hash2;
        }
        for (var x in temp) {
            var low;
            if (hash1[x] && hash2[x]) {
                if (hash1[x] <= hash2[x]) {
                    low = hash1[x];
                } else {
                    low = hash2[x];
                }
                for (var j = 0; j < low; j++) {
                    result.push(parseInt(x));
                }
            }
        }
        return result;
    };
    

Log in to reply
 

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