国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

【lintcode筆記】兩數組的交

2019-11-08 01:33:40
字體:
來源:轉載
供稿:網友

返回兩個數組的交

注意事項 Each element in the result must be unique. The result can be in any order. 樣例 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].

熟悉hash解法嘗試 負值失敗 嘗試OFFSET?

#include <stdio.h>#include <vector>using namespace std;class Solution {public: /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { // Write your code here int i=0,j=0,k=0; int m=nums1.size(); int n=nums2.size(); int *Hash = new int[m+n]; vector<int> nums3; for(int p=0; p<=m+n-1;p++) Hash[p]=0; while(i <= m-1){ int temp=0; temp = nums1[i]; if(Hash[temp] == 0) Hash[temp]++; i++; } while(j <= n-1){ int temp=0; temp = nums2[j]; if(Hash[temp] == 1) Hash[temp]++; j++; } while(k <= m+n-1){ if(Hash[k] == 2) nums3.push_back(k); k++; } delete[] Hash; return nums3; }};

第二種解法 常規 先排序后去重

#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>using namespace std;class Solution {public: /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { // Write your code here int i=0,j=0; int m=nums1.size(); int n=nums2.size(); vector<int> nums3; if(m==0 || n==0) return nums3; sort(nums1.begin(),nums1.end()); sort(nums2.begin(),nums2.end()); int temp; while(i <= m-1 && j <= n-1 ){ if(nums1[i] == nums2[j]){ if(temp != nums1[i]){ nums3.push_back(nums1[i]); temp = nums1[i]; } i++; j++; }else if(nums1[i] < nums2[j]){ i++; }else j++; } return nums3; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灌南县| 集安市| 宜君县| 乐陵市| 襄城县| 乐山市| 镇安县| 云龙县| 铅山县| 山西省| 互助| 凌云县| 彩票| 乌什县| 来宾市| 库尔勒市| 邵阳县| 聂拉木县| 太保市| 尼玛县| 密山市| 聂拉木县| 英山县| 仪征市| 乌鲁木齐县| 安徽省| 菏泽市| 昌邑市| 元谋县| 民县| 纳雍县| 建平县| 广宁县| 府谷县| 南郑县| 宣威市| 天台县| 阿图什市| 乐陵市| 始兴县| 北宁市|