We have many nodes implemented like this:
public class Person{
private String name;
private int id1;
private int id2;
private Node next; // or left/right, depending on what you're using.
}
- How to get
nameusingid1orid2in average less than O(n)? - How to print all
names in order ofid2in average O(n) or faster?
I thought of using a hash table ordered with id1 and a binary search tree organized by id2. As a beginner to data structures, I’m still unsure about this approach.
- Is this the simplest solution, in terms of ease of implementation
and data structures used? - Does using two data structures, both based on the same object, pose any problems? I’m wondering if “duplicating” data like I am here poses any problems for deleting and inserting, but other problems and solutions to the original questions are welcome too.
I would indeed use a
HashMap<Integer, Person>to store persons by ID1, and aTreeMap<Integer, Person>to store persons by ID2, sorted by ID2.The first one is O(1) to get the name by ID1. The second one is O(N) for iterating through all the values.
To answer your questions:
Collections.unmodifiableCollection()before returning it, to prevent a modification of the set from the outside.