# 极客时间李煜东算法训练营2021版二期【包完结】

2021-10-26 23:34:23  阅读：291  来源： 互联网

### 算法训练营2021版二期算法面试题

C++代码

``````class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if(nums1.empty() || nums2.empty())
return vector<int>();

unordered_set<int> st;
for(auto a : nums1)
st.insert(a);

vector<int> res;
for(int a : nums2)
{
if(st.count(a) > 0)
{
res.push_back(a);
st.erase(a);
}
}

return res;
}
};
``````

Python代码

``````class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
s = set()
res = []
for a in nums1:
for a in nums2:
if a in s:
res.append(a)
s.remove(a)
return res
``````

s首尾都有可能有空格，所以刚开始需要过滤掉收尾的空格
s可能全都是空格，这种情况输出空字符串

``````class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
while(!s.empty() && s.back() == ' ')
s.pop_back();

if(s.empty()) return;

reverse(s.begin(),s.end());

while(!s.empty() && s.back() == ' ')
s.pop_back();

string s1(s);
s.clear();

int len = s1.size();
int l = 0,r = 0;

while(r < len)
{
if(s1[r] == ' ')
{
reverse(s1.begin() + l,s1.begin() + r);
copy(s1.begin() + l,s1.begin() + r + 1,back_inserter(s));
while(s1[r] == ' ' && r < len) r++;
l = r;
}

r++;
}

reverse(s1.begin() + l,s1.begin() + r);
copy(s1.begin() + l,s1.begin() + r,back_inserter(s));
}
};

``````

。。。