首页 > 学院 > 开发设计 > 正文

LEETCODE--Intersection of Two Arrays

2019-11-14 10:31:47
字体:
来源:转载
供稿:网友

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. 方法一:用时短.ps:为了避免重复使用tag标记数组,在每次配对成功之后,将相应tag数组中的位置重新置0;

class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { int tag[1000] = {0}; int len1 = nums1.size(); int len2 = nums2.size(); for(int i = 0; i < len1; i++){ tag[nums1[i]] = 1; } vector<int> vec; for(int j = 0; j < len2; j++){ if(tag[nums2[j]] == 1){ tag[nums2[j]] = 0; vec.push_back(nums2[j]); } } return vec; }};

方法二: 用时略长先排序再比对。

class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int i = 0; int j = 0; int len1 = nums1.size(); int len2 = nums2.size(); vector<int> vec; int k = 0; while(i < len1 && j < len2){ if(nums1[i] == nums2[j]){ if(vec.size() == 0 || nums1[i] != vec[k-1]){ vec.push_back(nums1[i]); k++; i++; j++; }else{ i++; j++; } }else{ if(nums1[i] < nums2[j]) i++; else j++; } } return vec; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表