Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A.
We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.
These lists A and B may contain duplicates. If there are multiple answers, output any of them.
For example, given
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
We should return
[1, 4, 3, 2, 0]
as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.
Note:
A, B have equal lengths in range [1, 100].
A[i], B[i] are integers in range [0, 10^5].
题目大意:给两个数组A和B,B是A的同字母异序词,返回一个等长数组P,其中P[i] = j, 表示A的第i个元素在B的第j个元素处,如果有多个答案,返回一个即可~
分析:设置一个二维数组v,将数字i对应的在B数组中的下标放在v[i]中,这样遍历A数组,每次取出一个v[A[i]]放入ans数组对应的i下标处即可~
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public: vector<int> anagramMappings(vector<int>& A, vector<int>& B) { int len = A.size(); vector<int> ans(len), hash(len), v[100001]; for (int i = 0; i < len; i++) v[B[i]].push_back(i); for (int i = 0; i < len; i++) { ans[i] = v[A[i]].back(); v[A[i]].pop_back(); } return ans; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼