Skip to content

Latest commit

 

History

History
89 lines (59 loc) · 2.54 KB

File metadata and controls

89 lines (59 loc) · 2.54 KB

English Version

题目描述

给定两个列表 Aand B,并且 BA 的变位(即 B 是由 A 中的元素随机排列后组成的新列表)。

我们希望找出一个从 AB 的索引映射 P 。一个映射 P[i] = j 指的是列表 A 中的第 i 个元素出现于列表 B 中的第 j 个元素上。

列表 AB 可能出现重复元素。如果有多于一种答案,输出任意一种。

例如,给定

A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]

 

需要返回

[1, 4, 3, 2, 0]

P[0] = 1 ,因为 A 中的第 0 个元素出现于 B[1],而且 P[1] = 4 因为 A 中第 1 个元素出现于 B[4],以此类推。

 

注:

  1. A, B 有相同的长度,范围为 [1, 100]
  2. A[i], B[i] 都是范围在 [0, 10^5] 的整数。

 

解法

Python3

class Solution:
    def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]:
        mapper = collections.defaultdict(set)
        for i, num in enumerate(nums2):
            mapper[num].add(i)
        return [mapper[num].pop() for num in nums1]

Java

class Solution {
    public int[] anagramMappings(int[] nums1, int[] nums2) {
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums2.length; ++i) {
            map.computeIfAbsent(nums2[i], k -> new HashSet<>()).add(i);
        }
        int[] res = new int[nums1.length];
        for (int i = 0; i < nums1.length; ++i) {
            int idx = map.get(nums1[i]).iterator().next();
            res[i] = idx;
            map.get(nums1[i]).remove(idx);
        }
        return res;
    }
}

...