Skip to content

Latest commit

 

History

History
89 lines (72 loc) · 1.75 KB

350.两个数组的交集2.md

File metadata and controls

89 lines (72 loc) · 1.75 KB

350. 两个数组的交集 II

url

题目

给定两个数组,编写一个函数来计算它们的交集。

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]

方法

code

js

let intersect = (nums1, nums2) => {
    let list = [];
    for (let value of nums2) {
        if (nums1.includes(value)) {
            list.push(value);
            nums1.splice(nums1.findIndex(item => item === value), 1);
        }
    }
    return list;
};
console.log(intersect([1,2,2,1], [2, 2]))
console.log(intersect([4,9,5], [9,4,9,8,4]))

go

func intersect(nums1 []int, nums2 []int) []int {
	containInt := func (nums []int, item int) (int, bool) {
		for i, num := range nums {
			if num == item {
				return i, true
			}
		}
		return 0, false
	}
	var res []int
	for _, value := range nums2 {
		if i, ok := containInt(nums1, value); ok {
			res = append(res, value)
			nums1 = append(nums1[:i], nums1[i+1:]...)
		}
	}
	return res
}

java

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        ArrayList<Integer> list1 = new ArrayList<>();
        for (int num : nums1) {
            list1.add(num);
        }
        ArrayList<Integer> list2 = new ArrayList<>();
        for (int num : nums2) {
            if (list1.contains(num)) {
                list2.add(num);
                list1.remove(num);
            }
        }
        return list2.stream().mapToInt(Integer::valueOf).toArray();
        // int[] ans = new int[list2.size()];
        // for (int i = 0; i < list2.size(); i++) {
        //     ans[i] = list2.get(i);
        // }
        // return ans;
    }
}