Easy-30

来源:互联网 发布:linux git clone 路径 编辑:程序博客网 时间:2024/06/06 00:35

leetcode  349. Intersection of Two Arrays           

Given two arrays, write a function to compute their intersection.

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

AC:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {

    int* result=(int*)malloc((nums1Size>nums2Size?nums1Size:nums2Size)*sizeof(int));
    int length=0;
    for(int i=0;i<nums1Size;i++){
        for(int j=0;j<nums2Size;j++){
            if(nums1[i]==nums2[j]){
                result[length]=nums1[i];
                length++;
            }
        }
    }
    for(int i=0;i<length-1;i++){
        for(int j=i+1;j<length;j++){
            if(result[i]==result[j]){
                int k=result[j];
                result[j]=result[length-1];
                result[length-1]=k;
                length--;
                j--;
            }
        }
    }
    *returnSize=length;
    int* result1=(int*)malloc(length*sizeof(int));
    for(int i=0;i<length;i++)
    {
        result1[i]=result[i];
    }
    free(result);
    return result1;
}

tips: 特别简单的方法,时间复杂度很高。要注意的是在去重的时候,我选择把重复的放到末尾,然后长度减一,此时需要j--,这样避免从末尾换到第j个位置的元素没有进行查重处理。

0 0
原创粉丝点击