当前位置:网站首页>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 .
边栏推荐
- 3623. Merge two ordered arrays
- Cards are unpredictable
- Android Weather
- ArrayList underlying source code
- 三栏简约typecho主题Lanstar/蓝星typecho主题
- 深度学习每周期的步数多少合适?
- Most elements leetcode
- How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic returns of BBI, MTM, obv, CCI and priceosc indicators
- Remove duplicates from an ordered array
- Physical orbit simulation
猜你喜欢
随机推荐
The scope builder coroutinescope, runblocking and supervisorscope of kotlin collaboration processes run synchronously. How can other collaboration processes not be suspended when the collaboration pro
Characteristics of transactions - persistence (implementation principle)
[JS component] floating text
[server data recovery] successful cases of data loss recovery during data migration between storage servers
How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic returns of BBI, MTM, obv, CCI and priceosc indicators
sort
刘徽与《九章算术》《海岛算经》简介
Leetcode-15- sum of three numbers (medium)
Kotlin collaboration, the life cycle of a job
生态聚合NFT来袭,Metaverse Ape引领Web 3.0元宇宙新范式革命
The tle4253gs is a monolithic integrated low dropout tracking regulator in a small pg-dso-8 package.
Alexnet实现Caltech101数据集图像分类(pytorch实现)
What kind of experience is it to be a software test engineer in a state-owned enterprise: every day is like a war
What is dummy change?
Can GPU acceleration pytorch work?
Leetcode-17- letter combination of phone number (medium)
MySQL index
Deep learning model pruning
Unitywebrequest asynchronous Download
MySQL exception: com mysql. jdbc. PacketTooBigException: Packet for query is too large(4223215 > 4194304)









