当前位置:网站首页>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 .
边栏推荐
- 单片机串口中断以及消息收发处理——对接受信息进行判断实现控制
- [JS component] floating text
- Addition and modification of JPA
- Why is there always a space (63 or 2048 sectors) in front of the first partition when partitioning a disk
- What is pytorch? Explain the basic concepts of pytorch
- Androi天气
- [North Asia server data recovery] data recovery case of Hyper-V service paralysis caused by virtual machine file loss
- Continue when the condition is not asked, execute the parameter you compare
- Today's sleep quality record 74 points
- Key point detection data preparation and model design based on u-net Network -- detection model of four key points of industrial components
猜你喜欢

Most elements leetcode

Canvas game 2048 free map size

redis

Liu Hui and introduction to nine chapter arithmetic and island arithmetic
![[latex] insert picture](/img/0b/3304aaa03d3fea3ebb93b0348c3131.png)
[latex] insert picture

(01). Net Maui actual construction project

How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic returns of vrsi, bbiboll, WR, bias and RSI indicators

三栏简约typecho主题Lanstar/蓝星typecho主题

With a market value of more than trillion yuan and a sales volume of more than 100000 yuan for three consecutive months, will BYD become the strongest domestic brand?

Plusieurs catégories de tests logiciels sont claires à première vue
随机推荐
3623. Merge two ordered arrays
How many rounds of deep learning training? How many iterations?
数学知识整理:极值&最值,驻点,拉格朗日乘子
redis
5G工业网关在煤矿行业的应用优势
Build your own PE manually from winpe of ADK
[JS component] browse progress bar
Wal mechanism of MySQL
Binary tree -- using hierarchical sequence and middle sequence to determine a tree
Pipeline pipeline project construction
Leetcode-14- longest common prefix (simple)
Android Weather
spiral matrix visit Search a 2D Matrix
Why is there always a space (63 or 2048 sectors) in front of the first partition when partitioning a disk
Ecological convergence NFT attacks, metaverse ape leads the new paradigm revolution of Web 3.0 meta universe
軟件測試的幾種分類,一看就明了
Binary tree - right view
[JS] battle chess
Common skills for quantitative investment - drawing 2: drawing the moving average
The tle4253gs is a monolithic integrated low dropout tracking regulator in a small pg-dso-8 package.