use*_*904 7 java data-structures
我是Java的初学者.我有一些节点的示例数据:
A -> B
B -> F
C -> R
A -> B
B -> C
R -> C
Run Code Online (Sandbox Code Playgroud)
我已经拿出2个清单:[A,B,C,A,B,R]和[B,F,R,B,C,C]
但是,我应该如何存储对[AB,BF,CR,AB,BC,RC],以便找到唯一的对?通过唯一,我的意思是AB不等于BA.
1)所以基本上我想识别唯一的对.
2)我还想计算每个唯一对出现的次数.
编辑:
3)我也有兴趣找到每个节点连接的节点数.
4)有多少个不同的节点连接到每个节点
我正在努力决定是否真的需要编写自己的类或者是否有更简单的方法?
sri*_*eak 10
您可以创建一个自定义类来存储字符串对,然后使用a HashMap来跟踪计数
public class StringPair {
String leftString;
String rightString;
//NOTE: override hashcode and equals methods
}
Run Code Online (Sandbox Code Playgroud)
然后你可以HashMap用来跟踪计数:
Map<StringPair, Integer> pairCountMap = new HashMap<StringPair, Integer>();
if(pairCountMap.containsKey(aPairObject)) {
pairCountMap.put(aPairObject, pairCountMap.get(aPairObject)+1);
} else {
pairCountMap.put(aPairObject, 0);
}
Run Code Online (Sandbox Code Playgroud)
哈希表(数据结构)应该可以满足您的要求。在java中,你可以考虑类型HashMap<String,Integer>
key 是字符串对,Integer 是计数:
就像是:
{
"AB":2,
"CR":1,
"BF":1,
...
}
Run Code Online (Sandbox Code Playgroud)
找到唯一对的复杂性是O(n)
编辑
看来在这里放置代码有助于解释解决方案:
Map<String, Integer> map = new HashMap<String,Integer>();
//you have two lists with those strings, called list1 and list2.
// list1<String> and list2<String> have same size
String key = null;
for(int i=0;i<list1.size();i++){
key = list1.get(i) + list2.get(i);
if(map.containsKey(key))
map.get(key)++;
else
map.put(key,1);
}
//now the map has been filled, you can go through the map,
//and check the value, if value == 1, then the key is unique.
//for those value >1, you know, which string pair is not unique,
// and how many times it shows.
Run Code Online (Sandbox Code Playgroud)
代码不是用IDE编写的,所以可能会有错别字。