2019独角兽企业重金招聘Python工程师标准>>>
/**
* 功能:
[java] view plain copy
- /**
- * 思路:
- * 1)针对每个朋友ID,找出所在机器的位置:int machine_index=getMachineIDForUser(personID);
- * 2)转到编号为#machine_index的机器。
- * 3)在那台机器上,执行:Person friend=getPersonWithID(person_id)。
- *
- * 定义一个Server类,包含一份所有机器的列表,还有一个Machine类,代表一台单独的机器。通过散列表,有效地查找数据。
- *
- */
- class Server{
- HashMap<Integer,Machine> machines=new HashMap<Integer, Machine>();
- HashMap<Integer,Integer> personToMachineMap=new HashMap<Integer, Integer>();
- public Machine getMachineWithId(int machineID){
- return machines.get(machineID);
- }
- public int getMachineIDForUser(int personID){
- return personToMachineMap.get(personID);
- }
- public Person getPersonWithId(int personID){
- Integer machineID=getMachineIDForUser(personID);
- if(machineID==null)
- return null;
- Machine machine=getMachineWithId(machineID);
- if(machine==null)
- return null;
- return machine.getPersonWithId(personID);
- }
- }
- class Machine{
- public int machineID;
- public HashMap<Integer,Person> persons=new HashMap<Integer, Person>();
- public Person getPersonWithId(int personID){
- return persons.get(personID);
- }
- }
- class Person{
- private int personID;
- private ArrayList<Integer> friendID;
- public Person(int id){
- this.personID=id;
- }
- public int getID(){
- return this.personID;
- }
- public void addFriend(int id){
- this.friendID.add(id);
- }
- }
- /**
- * 优化:减少机器间跳转次数
- * 从一台机器跳转到另外一台机器的开销很昂贵,不要为了找到某个朋友就在机器之间任意跳转,而是试着批处理这些跳转动作。
- * 优化:智能划分用户和机器
- * 根据地域划分
- *
- * 问题:广度优先搜索要求标记访问过的节点,如何处理
- * 同一时间可能会执行很多搜索操作,因此直接编辑数据的做法并不妥当。可以利用散列表模仿节点的标记动作,以查询节点id,是否被访问过。
- */