美文网首页
349. Intersection of Two Arrays

349. Intersection of Two Arrays

作者: exialym | 来源:发表于2016-09-21 22:59 被阅读11次

    Given two arrays, write a function to compute their intersection.

    Example:
    Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

    Note:
    Each element in the result must be unique.
    The result can be in any order.

    利用数组的indexof

    var intersection = function(nums1, nums2) {
        var num1 = nums1.length;
        var num2 = nums2.length;
        return num1 < num2 ? compare(nums1,nums2,num1) : compare(nums2,nums1,num2);
        function compare(a,b,num) {
            var result = [];
            for (var i = 0;i<num;i++){
                if (result.indexOf(a[i])===-1) {
                    if (b.indexOf(a[i])!==-1) {
                        result.push(a[i]);
                    }
                }
            }
            return result;
        }
    };
    

    相关文章

      网友评论

          本文标题:349. Intersection of Two Arrays

          本文链接:https://www.haomeiwen.com/subject/fvxrettx.html