Intersection of Two Arrays

来源:互联网 发布:linux分頁地址 编辑:程序博客网 时间:2024/05/16 10:21

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.

Subscribe to see which companies asked this question.

根据问题分析,本题的目的是为了寻求两个数组的交集,以类作为实现。

我们首先创建一个函数:

vector<int> intersection(vector<int>& nums1, vector<int>& nums2)

其中nums1是第一个vector,nums2是第二个vector。下面我们将这个函数完善。

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        int temp;
   vector<int> nums3;
   int size = nums3.size();
   for(int i = 0; i < nums1.size(); i ++) {
   for(int j = 0; j < nums2.size(); j ++) {
       bool index = 0;
   if(nums1[i] == nums2[j]) {
   for(int k = 0; k < size; k++){
   if(nums3[k] == nums2[j])
   index = 1;
   }
   if(! index){
   nums3.push_back(nums2[j]);
   size ++;
   }
   }
   }
   }

   return nums3;

 }

下面编写mian函数,进行测试

int main() {
vector<int> nums1,nums2;
nums1.push_back(1);
nums1.push_back(2);
nums1.push_back(2);
nums1.push_back(1);

nums2.push_back(2);
nums2.push_back(1);

int n = intersection(nums1,nums2).size();
cout << "[";
for(int l = 0;l < n - 1; l ++){
cout<< intersection(nums1, nums2)[l] << ",";
}
cout << intersection(nums1,nums2)[n-1] << "]" <<endl;
return 0;
}

输出结果为[1,2],即测试通过。

0 0
原创粉丝点击