描述
????????給定兩個數組?nums1
?和?nums2
?,返回?它們的交集?。輸出結果中的每個元素一定是?唯一?的。我們可以?不考慮輸出結果的順序。(1 <= nums1.length, nums2.length <= 1000,0 <= nums1[i], nums2[i] <= 1000)
示例1
輸入:nums1 = [1,2,2,1], nums2 = [2,2]
輸出:[2]
示例2
輸入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出:[9,4]
解釋:[4,9] 也是可通過的
? ? ? ?思路:新建一個數組,將輸入的一個數組的值作為新建數組的下標,相應下標i的新建數組的值設為1,表示數i的個數有1個,如果輸入的另一個數組的值,在新建的數組的對應下標的數組值為1,將其數值設為2,表明數i在輸入的兩個數組中都有,再將新建數組中值為2的下標放入新數組中。
?
????????C語言
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
? ? ? ? int* arr=(int*)malloc(sizeof(int)*1000);
? ? ? ? //兩個集合相同元素的個數
? ? ? ? int count=0;
? ? ? ? for(int i=0;i<nums1Size;i++)
? ? ? ? {
? ? ? ? ? ? ? ? arr[nums1[i]]=1;
? ? ? ? }
? ? ? ? for(int i=0;i<nums2Size;i++)
? ? ? ? {
? ? ? ? ? ? //num2[i]為兩個數組共有元素
? ? ? ? ? ? if(arr[nums2[i]]==1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? arr[nums2[i]]=2;
? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? *returnSize=count;
????????//存放兩個數組的集合
? ? ? ? int* p=(int*)malloc(sizeof(int)*(nums1Size>nums2Size?nums1Size:nums2Size));
? ? ? ? int j=0;
? ? ? ? for(int i=0;i<1000;i++)
? ? ? ? {
? ? ? ? ? ? if(arr[i]==2)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? p[j++]=i;
? ? ? ? ? ? ? ? count--;
? ? ? ? ? ? }
? ? ? ? ? ? if(count==0)
? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? return p;
}
? ? ? ? Java
class Solution {
? ? public int[] intersection(int[] nums1, int[] nums2) {
? ? int[] temp = new int[1001];
? ? ? ? for (int i = 0; i < nums1.length; i++) {
? ? ? ? ? ? if (temp[nums1[i]]==0) temp[nums1[i]]=1;
? ? ? ? }
? ? ? ? int num = 0;
? ? ? ? for (int i = 0; i < nums2.length; i++) {
? ? ? ? ? ? if (temp[nums2[i]]==1){
? ? ? ? ? ? ? ? temp[nums2[i]]=2;
? ? ? ? ? ? ? ? num++;
? ? ? ? ? ? }?
? ? ? ? }
? ? ? ? int[] res = new int[num];
? ? ? ? for (int i = 0; i < 1001; i++) {
? ? ? ? ? ? if (temp[i]==2){
? ? ? ? ? ? ? ? res[--num] = i;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return res; ? ?
? ? }
}