350.两个数组的交集-ii

时游小于 1 分钟LeetCode

350.两个数组的交集-ii

/*
 * @lc app=leetcode.cn id=350 lang=typescript
 *
 * [350] 两个数组的交集 II
 */

// @lc code=start
function intersect(nums1: number[], nums2: number[]): number[] {
	// 先筛选交集数据
	const intersectionArr: number[] = [
		...new Set(nums1.filter(el => nums2.includes(el)))
	];

	// 分别生成两个哈希表,记录对应值出现次数
	interface NumberArray {
		[index: number]: number;
	}

	const num1Hash: NumberArray = {};
	const num2Hash: NumberArray = {};
	const finalArr: number[] = [];

	intersectionArr.map(el => {
		num1Hash[el] = getAllCount(nums1, el);
		num2Hash[el] = getAllCount(nums2, el);
	});

	intersectionArr.map(el => {
		if (num1Hash[el] < num2Hash[el]) {
			finalArr.push(...new Array(num1Hash[el]).fill(el));
		} else {
			finalArr.push(...new Array(num2Hash[el]).fill(el));
		}
	});
	return finalArr;
}

// 获取数组中该数据个数
function getAllCount(arr: number[], target: number): number {
	let count: number = 0;
	let currentIndex: number = arr.indexOf(target);
	while (currentIndex != -1) {
		count++;
		currentIndex = arr.indexOf(target, currentIndex + 1);
	}
	return count;
}

intersect([4, 9, 5], [9, 4, 9, 8, 4, 5]);
// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...