Leetcode 760: Find Anagram Mappings

问题描述:
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是数组长度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值