当前位置:网站首页>leetcode. 349. intersection of two arrays
leetcode. 349. intersection of two arrays
2022-06-13 01:03:00 【Didi dada】
- Intersection of two arrays
Given two arrays nums1 and nums2 , return Their intersection . Every element in the output must be only Of . We can Regardless of the order of the output results .
Example 1:
Input :nums1 = [1,2,2,1], nums2 = [2,2]
Output :[2]
Example 2:
Input :nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output :[9,4]
explain :[4,9] It is also passable
Method 1 : about python You can use set Fast implementation of properties and functions of
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
cur1 = set(nums1)
cur2 = set(nums2)
return list(cur1&cur2)
Method 2 :
C++ Realization , You can use map Judge
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> m;
vector<int> res;
for (auto it : nums1){
m[it]++;
}
for (auto it: nums2){
if (m[it]!=0){
res.emplace_back(it);
m[it]=0;
}
}
return res;
}
};
- Time complexity :O(n)
- Spatial complexity :O(n)
Method 3 : Sort + Double pointer ( have no thoughts of , Summarized in the solution )
If two arrays are ordered , You can use the double pointer method to get the intersection of two arrays .
First, sort the two arrays , Then use two pointers to traverse the two arrays . Predictably, the elements added to the array of answers must be incremented , In order to ensure the uniqueness of the added elements , We need to record additional variables pre Represents the last element added to the answer array .
At the beginning , The two pointers point to the heads of the two arrays . Compare the numbers in the two arrays pointed to by two pointers at a time , If the two numbers are not equal , Moves the pointer to the smaller number one bit to the right , If two numbers are equal , And the number is not equal to pre , Add this number to the answer and update pre Variable , Move both pointers to the right one bit at the same time . When at least one pointer is out of the range of the array , End of traversal .
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int length1 = nums1.size(), length2 = nums2.size();
int index1 = 0, index2 = 0;
vector<int> intersection;
while (index1 < length1 && index2 < length2) {
int num1 = nums1[index1], num2 = nums2[index2];
if (num1 == num2) {
// Ensure the uniqueness of the added elements
if (!intersection.size() || num1 != intersection.back()) {
intersection.push_back(num1);
}
index1++;
index2++;
} else if (num1 < num2) {
index1++;
} else {
index2++;
}
}
return intersection;
}
};
Time complexity : O ( m log m + n log n ) O(m \log m+n \log n) O(mlogm+nlogn), among m and n Are the lengths of the two arrays . The time complexity of sorting the two arrays is O ( m log m ) O(m \log m) O(mlogm) and O ( n log n ) O(n \log n) O(nlogn), The time complexity of finding intersection elements with double pointers is O ( m + n ) O(m+n) O(m+n), So the total time complexity is O ( m log m + n log n ) O(m \log m+n \log n) O(mlogm+nlogn).
Spatial complexity : O ( log m + log n ) O(\log m+\log n) O(logm+logn), among m and n Are the lengths of the two arrays . The space complexity mainly depends on the additional space used by sorting .
边栏推荐
- The seventh finals of the Blue Bridge Cup
- How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of DBCD, ROC, vroc, Cr and psy index strategy income
- Liu Hui and introduction to nine chapter arithmetic and island arithmetic
- Matrix fast power
- Pipeline流水线项目构建
- Illustrator tutorial, how to add dashes and arrows in illustrator?
- spiral matrix visit Search a 2D Matrix
- Common skills of quantitative investment - index part 2: detailed explanation of BOL (Bollinger line) index, its code implementation and drawing
- How many rounds of deep learning training? How many iterations?
- 深度学习模型剪枝
猜你喜欢

在国企做软件测试工程师是一种什么样的体验:每天过的像打仗一样

ArrayList underlying source code

切线与切平面

Alexnet实现Caltech101数据集图像分类(pytorch实现)

Hard (magnetic) disk (I)
![[003] embedded learning: creating project templates - using stm32cubemx](/img/18/43dfa98f1711e8e544828453e36812.jpg)
[003] embedded learning: creating project templates - using stm32cubemx

Five classic articles worth reading
![[network protocol] problems and solutions in the use of LwIP](/img/25/d064a761724936b8f35ee0c779e597.jpg)
[network protocol] problems and solutions in the use of LwIP

AOF持久化

.net core 抛异常对性能影响的求证之路
随机推荐
[latex] insert picture
什么是 dummy change?
What kind of experience is it to be a software test engineer in a state-owned enterprise: every day is like a war
Characteristics of transactions -- atomicity (implementation principle)
MySQL exception: com mysql. jdbc. PacketTooBigException: Packet for query is too large(4223215 > 4194304)
[virtual machine] notes on virtual machine environment problems
[JS component] calendar
Hard (magnetic) disk (II)
How the ET framework uses it to develop games
304. Merge two ordered arrays
Application advantages of 5g industrial gateway in coal industry
What is dummy change?
np.concatenate中axis的理解
[JS component] custom paging
Common skills of quantitative investment - index part 2: detailed explanation of BOL (Bollinger line) index, its code implementation and drawing
5G工业网关在煤矿行业的应用优势
今日睡眠质量记录74分
Hard (magnetic) disk (I)
MySQL performance analysis - explain
[Latex] 插入圖片