照例來段碎碎念:
時隔8天,即將結束回家家度假生活的我,又拾起了電腦。在家里寬敞的戶外,同時用著簡書和Leetcode,不遠處能看到Little Dog,雖然隨著日落,突然出現了可惡的蚊子,我依然想堅持在戶外記錄下美好的下午。
今天的問題是:如何找到兩個數字串的交集呢?
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
我的解法
先把兩個數字串排序,我用了自帶的sort函數。
模擬我們人手動找相同數字的步驟,找到相同的數字就輸出。
12ms的速度,不是最優。
但我這個先排序的方法,對于“大數據”就無能為力了,在下能力還不會解決存不下時的情況。
巨坑,吃一塹長一智
刷題的最大樂趣,其實莫過于解決各種奇葩的錯誤。每每嘆氣曰:“真是奇了怪了”。比如本題中我的這句聲明:
vector<int> tmp = nums1;
之前用vector<int>& tmp;
定義的tmp,一直導致nums2序列錯誤=。=
一個‘&’符號是導致本質巨大差距的,我本知指針和地址的奇妙原理,卻在使用的時候忽略了它。導致這道題刷了好久。
貼上我寫的不是最佳速度的AC代碼:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end() );
sort(nums2.begin(), nums2.end() );
vector<int> ans ;
if(nums1.size() > nums2.size() ){
vector<int> tmp = nums1; //之前用vector<int>& tmp定義的,一直導致nums2序列錯誤=。=
nums1 = nums2;
nums2 = tmp;
}
int j = 0;
for(int i = 0; i < nums1.size(); i++ ){//前面保證1是較小的。
//cout<<i<<':'<<nums1[i]<<';'<<j<<':'<<nums2[j]<<endl;
if(j >= nums2.size())
break;
if(nums1[i] == nums2[j]){
ans.push_back ( nums1[i] ); //加入這個數
j++;
}else if (nums1[i] > nums2[j]){ //如果1比2的當前數字大,需要挪動2,1不動。
j++;
i--;
}
}
return ans;
}
};
實際上,曾經類似的題目,我用相同的方法解決過。
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.
我的解法
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//先將兩個容器升序排序
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
//聲明2個容器的指標
int i = 0;
int j = 0;
int len1 = nums1.size();
int len2 = nums2.size();
vector<int> ans;
while(i < len1 && j < len2){ //ij有任何一個到頭了就結束
if(nums1.at(i) == nums2.at(j)){
if(!ans.size() || nums1.at(i) > ans.back()){
//不等于ans最后一個值或ans還沒有第一個值
ans.push_back(nums1.at(i));
}
i++;
j++;
}else if(nums1.at(i) < nums2.at(j)){
//1容器的值比2容器的值小,則1指標++,2指標不動。
i++;
}else{
j++;
}
}
return ans;
}
};
18天之隔,寫法完全不同
同樣是一樣的思路,同樣一個我,卻用了不同的寫法。再一次論證:我是善變的!哈哈,還是因為我目前手法不熟練,沒有形成自有的規范和套路吧。
在家安閑的刷題寫簡書還是很休閑有趣的,明晚回京,還是家里好。
——End——