有两条序列A,B,每个序列中以空格分隔每组元素,接下来我需要查找A中每一个元素在B中出现的位置,假设查找A【1】在B中出现的位置B【p】,那么B【p】后面需要出现A【1】后面的全部元素,如果这样我们称p合法,否则p位置不合法,请你编写c++代码找出A中每个元素在B中的合法位置
时间: 2024-03-05 13:53:38 浏览: 15
好,以下是C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> findValidPositions(vector<int>& A, vector<int>& B) {
vector<int> res;
unordered_map<int, int> posMap; // 记录B中每个元素的位置
for (int i = 0; i < B.size(); i++) {
posMap[B[i]] = i;
}
for (int i = 0; i < A.size(); i++) {
int startPos = posMap[A[i]]; // A[i]在B中的起始位置
bool isValid = true;
for (int j = i + 1; j < A.size(); j++) {
if (posMap[A[j]] < startPos) { // A[j]在A[i]前面
isValid = false;
break;
}
startPos = posMap[A[j]]; // 更新A[j]在B中的位置
}
if (isValid) {
res.push_back(posMap[A[i]]);
}
}
return res;
}
int main() {
vector<int> A = {1, 2, 3};
vector<int> B = {2, 1, 3, 4, 5, 6, 7, 8, 9};
vector<int> res = findValidPositions(A, B);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " "; // 输出合法位置
}
return 0;
}
```
解释一下代码的实现思路:
首先用一个`unordered_map`记录B中每个元素的位置,然后遍历A中的每个元素,在B中找到其起始位置,然后依次找后面的元素是否满足在B中出现的位置是递增的,如果满足就将该位置记录下来,最后输出所有合法位置。