760. Find Anagram Mappings
760. Find Anagram Mappings Given two lists Aand 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. Solution 1 : Use an int[] array to store the res Use a helper func to get the index of A[I] in B and put the index at res[I] Return res class Solution { public int[] anagramMappings(int[] A, int[] B) { int[] res = new int[A.length]; for(int i = 0; i < A.length; i++){ res[i] = helper(A[i], B); } return res; } private int helper(int target, int[] B){ for(int i = 0; i < B.length; i++){ if(B[i] == target) return i; } return -1; } } Solution 2 : use a hash map to optimize time class Solution { public int[] anagramMappings(int[] A, int[] B) { // use a hashmap to extract information from B, key is the element value in B, value is the index of this element in B // loop thru every element in A and loop up its index in B int[] res = new int[A.length]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < B.length; i++){ map.put(B[i], i); } for(int j = 0; j < A.length; j++){ res[j] = map.get(A[j]); } return res; } } class Solution { public int[] anagramMappings(int[] A, int[] B) { // use a hashmap to extract information from B, key is the element value in B, value is the index of this element in B // loop thru every element in A and loop up its index in B int[] res = new int[A.length]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < B.length; i++){ map.put(B[i], i); } for(int i = 0; i < A.length; i++){ // also okay to use i , same var name as above, is it good practice tho? res[i] = map.get(A[i]); } return res; } }
posted on 2018-09-20 18:25 猪猪🐷 阅读(105) 评论(0) 收藏 举报
浙公网安备 33010602011771号