返回介绍

solution / 0700-0799 / 0760.Find Anagram Mappings / README_EN

发布于 2024-06-17 01:03:34 字数 2857 浏览 0 评论 0 收藏 0

760. Find Anagram Mappings

中文文档

Description

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.

 

Example 1:

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.

Example 2:

Input: nums1 = [84,46], nums2 = [84,46]
Output: [0,1]

 

Constraints:

  • 1 <= nums1.length <= 100
  • nums2.length == nums1.length
  • 0 <= nums1[i], nums2[i] <= 105
  • nums2 is an anagram of nums1.

Solutions

Solution 1

class Solution:
  def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]:
    mapper = defaultdict(set)
    for i, num in enumerate(nums2):
      mapper[num].add(i)
    return [mapper[num].pop() for num in nums1]
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;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文