【LeetCode】760. Find Anagram Mappings 解题报告(C++)


题目地址:https://leetcode-cn.com/problems/find-anagram-mappings/

题目描述

Given two lists A and B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A.

We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.

These lists A and B may contain duplicates. If there are multiple answers, output any of them.

For example, given

A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
We should return
[1, 4, 3, 2, 0]
as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.

Note:

  1. A, B have equal lengths in range [1, 100].
  2. A[i], B[i] are integers in range [0, 10^5].

题目大意

给定两个列表 Aand B,并且 B 是 A 的变位(即 B 是由 A 中的元素随机排列后组成的新列表)。
我们希望找出一个从 A 到 B 的索引映射 P 。一个映射 P[i] = j 指的是列表 A 中的第 i 个元素出现于列表 B 中的第 j 个元素上。
列表 A 和 B 可能出现重复元素。如果有多于一种答案,输出任意一种。

解题方法

遍历

看了眼A的长度,只有100,那么最快的方法就是直接暴力求解,找出A的每个元素在B中出现的位置索引。

C++代码如下:

class Solution {
public:
    vector<int> anagramMappings(vector<int>& A, vector<int>& B) {
        vector<int> res(A.size());
        for (int i = 0; i < A.size(); ++i) {
            for (int j = 0; j < B.size(); ++j) {
                if (A[i] == B[j]) {
                    res[i] = j;
                }
            }
        }
        return res;
    }
};

日期

2019 年 9 月 18 日 —— 今日又是九一八

posted @ 2019-09-18 17:16  负雪明烛  阅读(21)  评论(0编辑  收藏  举报