精華區beta Marginalman 關於我們 聯絡資訊
最近好多easy 又水了一天 亂寫一通 349. Intersection of Two Arrays Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> cnt(1001,0); unordered_set<int> a; unordered_set<int> b; vector<int> ans; for(auto i : nums1) { a.insert(i); } for(auto i : nums2) { b.insert(i); } for(auto i : a) { cnt[i]++; } for(auto i : b) { cnt[i]--; if(cnt[i] == 0) { ans.push_back(i); } } return ans; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.228.146.144 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1710050476.A.AF2.html ※ 編輯: DJYOSHITAKA (125.228.146.144 臺灣), 03/10/2024 14:01:26
JIWP: 大師 03/10 14:06
Rushia: return set(nums1).intersection(set(nums2)) 03/10 14:08
tzyysang: 為什麼用兩個set還要count 好怪ㄛ 03/10 14:14
Rushia: 只要用一個SET就好 第一個記錄nums1 然後for in nums2 03/10 14:15
Rushia: 如果遇到set1有的數字就把他加進ans 然後把數字從set1移除 03/10 14:16
DJYOSHITAKA: 就沒想太多 對不起 03/10 14:18
DJYOSHITAKA: 一個就好 03/10 14:19
DJYOSHITAKA: 應該是下意識沒想到set.find或set.count吧 太不熟ㄌ 03/10 14:31