简单问题,熟悉下 C 的哈希表,使用第三方库:
C:
typedef struct Hash { int key; UT_hash_handle hh; } Hash; int hashExit(int key, Hash **hashs) { Hash *target = NULL; HASH_FIND_INT(*hashs, &key, target); if (target == NULL) return 0; return 1; } int hashAdd(int key, Hash **hashs) { Hash *target = (Hash *)malloc(sizeof(Hash)); target->key = key; if (hashExit(key, hashs) == 1) return 0; HASH_ADD_INT(*hashs, key, target); return 1; } void hashClear(Hash **set) { struct Hash *current, *tmp; HASH_ITER(hh, *set, current, tmp) { HASH_DEL(*set, current); free(current); } } /** * Note: The returned array must be malloced, assume caller calls free(). */ int *intersection(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) { Hash *nums1Hashs = NULL, *reHashs = NULL; int smallSize = nums1Size > nums2Size ? nums2Size : nums1Size; int *reArr = (int *)malloc(sizeof(int) * smallSize); int rePoint = 0; for (int i = 0; i < nums1Size; i++) hashAdd(nums1[i], &nums1Hashs); for (int i = 0; i < nums2Size; i++) { if (hashExit(nums2[i], &nums1Hashs) == 1) { if (hashAdd(nums2[i], &reHashs) == 1) { reArr[rePoint] = nums2[i]; rePoint++; } } } hashClear(&nums1Hashs); hashClear(&reHashs); *returnSize = rePoint; return reArr; }
JAVA:
class Solution { public final int[] intersection(int[] nums1, int[] nums2) { Set<Integer> nums1Set = new HashSet<Integer>(); for (int i = 0; i < nums1.length; i++) nums1Set.add(nums1[i]); Set<Integer> reSet = new HashSet<Integer>(); for (int i = 0; i < nums2.length; i++) { if (nums1Set.contains(nums2[i])) reSet.add(nums2[i]); } int[] reArr = new int[reSet.size()]; int i = 0; Iterator<Integer> iterator = reSet.iterator(); while (iterator.hasNext()) { reArr[i] = iterator.next(); i++; } return reArr; } }
JS:
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function (nums1, nums2) { let nums1Set = new Set(nums1), reSet = new Set(), reArr = []; for (let i = 0; i < nums1.length; i++) nums1Set.add(nums1[i]); let re = [], point = 0; for (let i = 0; i < nums2.length; i++) { if (nums1Set.has(nums2[i])) { if (reSet.has(nums2[i])) continue; reSet.add(nums2[i]); reArr.push(nums2[i]); } } return reArr; };