760. Find Anagram Mappings

LeetCode original: C# #array #csharp #hash-table #leetcode #search
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

: easy

Вам given два целочисленных tableauа nums1 и nums2, где nums2 - анаграмма nums1. Оба tableauа могут содержать дубликаты. return индексное отображение tableauа mapping из nums1 в nums2, где mapping[i] = j означает, что i-й element в nums1 появляется в nums2 по индексу j. Если ответов несколько, return любой из них. tableau a является анаграммой tableauа b означает, что b создается путем случайного изменения порядка elementов в a.

Exemple:

Input: nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28]

Output: [1,4,3,2,0]

C# solution

correspondant/original
using System;
using System.Collections.Generic;
public class Solution {
    public int[] AnagramMapping(int[] nums1, int[] nums2) {
        var indexMap = new Dictionary<int, List<int>>();
        for (int i = 0; i < nums2.Length; i++) {
            if (!indexMap.ContainsKey(nums2[i])) {
                indexMap[nums2[i]] = new List<int>();
            }
            indexMap[nums2[i]].Add(i);
        }
        
        var mapping = new int[nums1.Length];
        for (int i = 0; i < nums1.Length; i++) {
            var indices = indexMap[nums1[i]];
            mapping[i] = indices[indices.Count - 1];
            indices.RemoveAt(indices.Count - 1);
        }
        
        return mapping;
    }
}

C++ solution

brouillon automatique, à relire avant soumission
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& AnagramMapping(vector<int>& nums1, vector<int>& nums2) {
        var indexMap = new unordered_map<int, List<int>>();
        for (int i = 0; i < nums2.size(); i++) {
            if (!indexMap.count(nums2[i])) {
                indexMap[nums2[i]] = new List<int>();
            }
            indexMap[nums2[i]].push_back(i);
        }
        
        var mapping = new int[nums1.size()];
        for (int i = 0; i < nums1.size(); i++) {
            var indices = indexMap[nums1[i]];
            mapping[i] = indices[indices.size() - 1];
            indices.RemoveAt(indices.size() - 1);
        }
        
        return mapping;
    }
}

Java solution

correspondant/original
import java.util.*;

public class Solution {
    public int[] anagramMapping(int[] nums1, int[] nums2) {
        Map<Integer, List<Integer>> indexMap = new HashMap<>();
        for (int i = 0; i < nums2.length; i++) {
            indexMap.computeIfAbsent(nums2[i], k -> new ArrayList<>()).add(i);
        }
        
        int[] mapping = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            mapping[i] = indexMap.get(nums1[i]).remove(indexMap.get(nums1[i]).size() - 1);
        }
        
        return mapping;
    }

JavaScript solution

correspondant/original
function anagramMapping(nums1, nums2) {
    let indexMap = new Map();
    nums2.forEach((num, i) => {
        if (!indexMap.has(num)) {
            indexMap.set(num, []);
        }
        indexMap.get(num).push(i);
    });
    
    return nums1.map(num => indexMap.get(num).pop());
}

Python solution

correspondant/original
def anagramMapping(nums1, nums2):
    index_map = {}
    for i, num in enumerate(nums2):
        if num in index_map:
            index_map[num].append(i)
        else:
            index_map[num] = [i]
    
    mapping = []
    for num in nums1:
        mapping.append(index_ma

Algorithm

Создайте словарь для хранения индексов elementов в nums2.

Пройдите по elementам tableauа nums1 и для каждого elementа find соответствующий индекс в nums2, используя словарь.

return tableau индексов.

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.