Pregunta de entrevista de Google

Invert a Map e.g 1: {a,b} 2: {c,d} becomes a:1 b:1 c:2 d2

Respuestas de entrevistas

Anónimo

31 may 2013

Since no one has answered the question, I figure I'll throw in my 2 cents. It seems fairly simple; if you're using java (and probably most OO languages), you have access to all the keys that you've inserted into the map through a function call. Simply iterate through your keys to get the value from the map for each key, and put that value in a temporary variable (I'll call it tempValue). Then, save the key before it's destroyed in the next step (let's call it tempKey). Then, remove the entry from the hash table that correlated to that value (i.e., map.remove(key) I think it is). Now, do a map.put(tempValue, tempKey). You've now done your first iteration; repeat these steps for the rest of the hash's keys and you're done.

Anónimo

14 oct 2013

In C++11 (mainly for the simplified for loop syntax), assuming that the question is about transforming map> to map> below is my solution: map> oldMap; list one; one.push_back('a'); one.push_back('b'); oldMap.insert(make_pair(1, one)); list two; two.push_back('c'); two.push_back('d'); oldMap.insert(make_pair(2, two)); map> newMap; for(pair> p : oldMap) { for(char c : p.second) { newMap[c].push_back(p.first); } }

Anónimo

22 abr 2014

Map map1 = new HashMap(); Map map2 = new HashMap(); for(Integer key: map1.keySet()){ for (int i=0; i < a.size(); i++){ map2.put(map1.get(key).get(i).toString(), key); } } for(String key: map2.keySet()) System.out.println(key + ": " + map2.get(key));