760. Find Anagram Mappings(bingo)

Given two listsAandB, andBis an anagram ofA.Bis an anagram ofAmeansBis made by randomizing the order of the elements inA.

We want to find anindex mappingP, fromAtoB. A mappingP[i] = jmeans theith element inAappears inBat indexj.

These listsAandBmay 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:

A, Bhave equal lengths in range[1, 100].

A[i], B[i]are integers in range[0, 10^5].

意思大致就是:给两个数组,数组A和数组B中有相同的数字,把数组A中每个数字在数组B中对应位置的下标输出

本来想两个for循环,遍历,但是觉得这样有可能出现TML,放弃了这种做法。

后来又想把B数组放到一个Map中(数字(key):下标(value)),遍历A数组的时候查找Map中的key,返回value就ok了,执行时间7ms。

Solution:bingo

public static void main(String args[]){  

int[]A = {12, 28, 46, 32, 50};  

int[]B = {50, 12, 32, 46, 28};  

        System.out.print(anagramMappings(A,B));  

    }  

    public static int[] anagramMappings(int[] A, int[] B) {  

int[]newInt = new int[A.length];  

Mapbmaping = new HashMap();  

for (inti=0;i

            bmaping.put(B[i],i);  

        }  

for (inti=0;i

            if (bmaping.containsKey(A[i])){  

//返回的是value值------>V get(Object key);  

into = (int)bmaping.get(A[i]);  

                newInt[i] = o;  

            }  

        }  

        return newInt;  

    }  

注:.get()方法返回的是Value值

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容