问题描述:
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 array mapping from nums1 to nums2 where mapping[i] = j means the ith element in nums1 appears in nums2 at index j. 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.
nums1和nums2是“同素异形体”,他们由相同的元素组成但顺序不同。现在要找出nums1元素在nums2的位置,用一个数组记录全部位置
思路:
由于元素可重复,所以不能简单地使用哈希表。键值对中的“值”要用另外一个set代替(也可以用list,但搜索成本更高)。代码分为构建hashmap和检索hashmap两部分组成。注意在检索hashmap时我们每次抽取该元素对应的set里面任意元素(如题目所述),写到数组中,并立刻从set中删掉。
代码如下:
class Solution {
public int[] anagramMappings(int[] nums1, int[] nums2) {
Map<Integer, Set<Integer>> map=new HashMap<>();
for(int i=0; i<nums2.length; i++){
if(!map.containsKey(nums2[i])){
Set<Integer> set=new HashSet<>();
set.add(i);
map.put(nums2[i], set);
}
else{
Set<Integer> tempSet=map.get(nums2[i]);
tempSet.add(i);
map.put(nums2[i], tempSet);
}
}
int[] ans=new int[nums1.length];
for(int i=0; i<nums1.length; i++){
Set<Integer> tempSet=map.get(nums1[i]);
for(Integer a: tempSet){
ans[i]=a;
tempSet.remove(a);
break;
}
}
return ans;
}
}
时间复杂度: O(n), n是数组长度