社交关系中的共同好友数目计算(一度好友与二度好友)
生活随笔
收集整理的這篇文章主要介紹了
社交关系中的共同好友数目计算(一度好友与二度好友)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 public class test1 {
2 /**
3 * 思路:如果A與某人有共同好友,則該人必出現在二度好友中
4 * 不在二度好友中的,則與A的共同好友數必然為0
5 * 故只需遍歷所有的二度好友即可,但是不要將那些無共同好友的一度好友忘記!也就是初始化firstout
6 * @param args
7 */
8
9
10 // directs為A的一度好友list,indirects為Map<String,List<String>代表一度好友的一度好友(不包括A)映射關系表
11 // firstout為A與其一度好友的共同好友數Map,secondout為A與其二度好友的共同好友數Map
12 public static void main(String[] args) {
13
14 String directsString = "BDEH";
15 String bString = "CD";
16 String dString = "B,E,G,G";
17 String eString = "C,D";
18 String hString = "I";
19 List<String> directs = stringToList(directsString);
20
21
22 Map<String, List<String>> indirects = new HashMap<String, List<String>>();
23 indirects.put("B", stringToList(bString));
24 indirects.put("D", stringToList(dString));
25 indirects.put("E", stringToList(eString));
26 indirects.put("H", stringToList(hString));
27
28 Map<String, Integer> firstout = new HashMap<String, Integer>();//用于存放A與一度好友的共同好友數目
29 Map<String, Integer> secondout = new HashMap<String, Integer>();//用于存放A與二度好友的共同好友數目
30
31 //由于遍歷所有二度好友,先去考慮在不在fistout中,如果不在則必為二度好友,然后才去考慮在不在secondout中做最后處理,
32 //故firstout需要進行初始化,保證fistout+secondout包含所有A的一度好友與二度好友
33 for(String str : directs) {
34 firstout.put(str, 0);
35 }
36
37 for(Map.Entry<String, List<String>> entry : indirects.entrySet()) {
38 for(String id2 : entry.getValue()) {
39 Integer value = firstout.get(id2);
40 if(value != null) {
41 firstout.put(id2, value+1);
42 }else {
43 if(secondout.get(id2) == null) {
44 secondout.put(id2, 1);
45 }else {
46 secondout.put(id2, secondout.get(id2) + 1);
47 }
48 }
49 }
50 }
51
52 System.out.println("A與一度好友B的共同好友數: " + firstout.get("B"));
53 System.out.println("A與一度好友D的共同好友數: " + firstout.get("D"));
54 System.out.println("A與二度好友C的共同好友數: " + secondout.get("C"));
55 System.out.println("A與二度好友I的共同好友數: " + secondout.get("I"));
56 }
57
58 public static List<String> stringToList(String str) {
59 List<String> list = new ArrayList<String>();
60 for (int i = 0; i < str.length(); i++) {
61 list.add(str.charAt(i) + "");
62 }
63 return list;
64 }
65 }
輸出結果:
A與一度好友B的共同好友數: 1
A與一度好友D的共同好友數: 2
A與二度好友C的共同好友數: 2
A與二度好友I的共同好友數: 1
總結
以上是生活随笔為你收集整理的社交关系中的共同好友数目计算(一度好友与二度好友)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批量修改Service Order de
- 下一篇: 批量删除指定user和transacti