日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】排序

發(fā)布時間:2025/7/25 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】排序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

[349] Intersection of Two Arrays [Easy]

兩個無序可重復數(shù)組找交集, 交集要求元素唯一。

Given?nums1?=?[1, 2, 2, 1],?nums2?=?[2, 2], return?[2].

思路:1、兩個unordered_set 可以去重; 2、先排序,雙指針

1 //Space:O(N); Time: 0(N) 2 //unordered_set insert, emplace, find, delete O(1) 3 4 class Solution { 5 public: 6 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 7 unordered_set<int> st1; 8 for (auto ele: nums1) { 9 st1.emplace(ele); 10 } 11 unordered_set<int> st2; 12 for (auto ele: nums2) { 13 if (st1.find(ele) != st1.end()) { 14 st2.emplace(ele); 15 } 16 } 17 vector<int> ans; 18 for (auto ele: st2) { 19 ans.push_back(ele); 20 } 21 return ans; 22 } 23 }; View Code

?

1 //space: no extra sapce, time(nlog(n)) 2 //two pointers 3 class Solution { 4 public: 5 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 6 sort(nums1.begin(), nums1.end()); 7 sort(nums2.begin(), nums2.end()); 8 vector<int>::size_type idx1 = 0, idx2 = 0; 9 vector<int> ans; 10 while(idx1 < nums1.size() && idx2 < nums2.size()) { 11 if(nums1[idx1] == nums2[idx2]) { 12 if (ans.empty() || nums1[idx1] != ans.back()) { //使用api之前一定先做條件檢測 13 ans.push_back(nums1[idx1]); 14 } 15 idx1++, idx2++; 16 } else if (nums1[idx1] < nums2[idx2]) { 17 ++idx1; 18 } else { 19 ++idx2; 20 } 21 } 22 return ans; 23 } 24 }; View Code

?

轉載于:https://www.cnblogs.com/zhangwanying/p/6661503.html

總結

以上是生活随笔為你收集整理的【LeetCode】排序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。