I have a Map
and a List
. The List
should be sorted based on the Map
key values. Eg:
Map = (<2,"Andy">,<4,"Karl">)
List = ("Kathy","Andy","Yiri","Jun","Karl")
I have to sort the List in such a way that at index : (2 : Andy) should be there and at index (4 : Karl) should be there. For rest of elements order does not matter. Rest of Conditions are :
I am able to do this in 2 loops , I was curious to know if it is possible to achieve this in a single Loop.
You can use 1 loop to loop through all keys in the map, and search for the object in the List with indexOf(Object)
, then use set
twice to swap the object to the correct position.
Pseudocode (that looks like Java):
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
for (Map.Entry<Integer, String> e: entrySet) {
int index;
if ((index = list.indexOf(e.getValue())) >= 0 && index != e.getKey()) {
list.set(index, list.set(e.getKey(), e.getValue()));
}
}
Well, complexity is not that good: O(nk) where n is the number of elements in the List and k is the number of elements in the Map.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.