You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both arrays may contain duplicates.
Return an index mapping arraymappingfromnums1tonums2wheremapping[i] = jmeans theithelement innums1appears innums2at indexj. If there are multiple answers, return any of them.
An array a is an anagram of an array b means b is made by randomizing the order of the elements in a.
Input: nums1 =[12,28,46,32,50], nums2 =[50,12,32,46,28]Output: [1,4,3,2,0]Explanation: As mapping[0]=1 because the 0th element of nums1 appears at nums2[1], and mapping[1]=4 because the 1st element of nums1 appears at nums2[4], and so on.
Since nums2 is an anagram of nums1, every element in nums1 appears in nums2. We can map each value in nums2 to its indices, then for each value in nums1, pick an unused index from nums2.
classSolution {
publicint[]anagramMappings(int[] nums1, int[] nums2) {
Map<Integer, Deque<Integer>> idx =new HashMap<>();
for (int i = 0; i < nums2.length; i++) idx.computeIfAbsent(nums2[i], k ->new ArrayDeque<>()).add(i);
int[] ans =newint[nums1.length];
for (int i = 0; i < nums1.length; i++) ans[i]= idx.get(nums1[i]).removeLast();
return ans;
}
}
1
2
3
4
5
6
7
classSolution {
funanagramMappings(nums1: IntArray, nums2: IntArray): IntArray {
val idx = mutableMapOf<Int, ArrayDeque<Int>>()
for ((i, x) in nums2.withIndex()) idx.getOrPut(x) { ArrayDeque() }.add(i)
return nums1.map { idx[it]!!.removeLast() }.toIntArray()
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defanagramMappings(self, nums1: list[int], nums2: list[int]) -> list[int]:
from collections import defaultdict
idx = defaultdict(list)
for i, x in enumerate(nums2):
idx[x].append(i)
ans = []
for x in nums1:
ans.append(idx[x].pop())
return ans
1
2
3
4
5
6
7
8
9
10
use std::collections::HashMap;
impl Solution {
pubfnanagram_mappings(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
letmut idx = HashMap::new();
for (i, &x) in nums2.iter().enumerate() {
idx.entry(x).or_insert(vec![]).push(i asi32);
}
nums1.iter().map(|&x| idx.get_mut(&x).unwrap().pop().unwrap()).collect()
}
}