Leetcode-350-Intersection of Two Arrays II

题目要求:Given two arrays, write a function to compute their intersection.

求两个数组的并集

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

注意:所求得的数组中有重复元素。

解题思路:1,函数compare():将输入的两个数组按升序排列

2.对排列好的另个数组进行比较,若出现相等元素就将其push到一个新建数组里

代码如下:

<script type="text/javascript">
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function(nums1, nums2) {
    var num = [];
    var t = 0;
    nums1.sort(compare);
    nums2.sort(compare);
    for(var i = 0,j = 0; i < nums1.length && j < nums2.length;){
    if (nums1[i] == nums2[j]) {
    num.push(nums1[i]);
    i++;
    j++;
    } else if (nums1[i] < nums2[j]) {
    i++;
    } else if (nums1[i] > nums2[j]) {
    j++;
    }
    }
    function compare(value1,value2){
    if (value1 < value2) {
    return -1;
    } else if (value1 > value2) {
    return 1;
    } else {
    return 0;
    }
    }
    // alert(nums1);
    // alert(nums2);
    alert(num);
};
// intersect([61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,4],[5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48]);
// intersect([0,1,5,10,15],[0,1,5,10,15]);
intersect([1,2,2,3,4,4,4],[2,4,4]);
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值