private void merge(ArrayList<String> operations, ArrayList<LinkedHashSet<String>> setOfStrings) {
String toMerge = operations.get(1);
String fromMerge = operations.get(2);
boolean enteredFirstToMerge = false;
boolean enteredFirstForMerge = false;
// references that points one on toMerge and the other on fromMerge
LinkedHashSet<String> toMergeAndAfterDelete = null;
LinkedHashSet<String> addOnFromMerge = null;
for (LinkedHashSet<String> subSet : setOfStrings) {
if (subSet.contains(toMerge) && subSet.contains(fromMerge))
break;
else {
if (subSet.contains(toMerge) && !enteredFirstToMerge) {
toMergeAndAfterDelete = subSet;
enteredFirstToMerge = true;
}
if (subSet.contains(fromMerge) && !enteredFirstForMerge) {
addOnFromMerge = subSet;
enteredFirstForMerge = true;
}
if ((enteredFirstForMerge && enteredFirstToMerge)) {
break;
}
}
}
/***********************************************/
//outside Loop i call the remove on the arraylist
//that are very expensive
/*************************************************/
if (enteredFirstForMerge && enteredFirstToMerge) {
// first i delete from the array the linkedHashSet toMerge and
// fromMerge and after i add a
// new linkedHashSet with the subSets merged
setOfStrings.remove(toMergeAndAfterDelete);
setOfStrings.remove(addToMergeOnFromMerge);
addOnFromMerge.addAll(toMergeAndAfterDelete);
setOfStrings.add(addOnFromMerge);
}
}
This function takes as parameter an arrayList
of operations, and an ArrayList<LinkedHashSet<String>>
:
For the arrayList
of operations
, I always get a specific position, so I don't iterate. It is always \$O(1)\$.
For example, if I have as operation move foo bar
, I have to do these steps:
First of all, I have to find where are located
foo
andbar
:Inside
setOfStrings
, I can have this situation:position x : {bar tree hotel} ... position y : {foo lemon coffee}
When I find them, I have to concat the foo string into bar string
in this way:
position x : {bar tree hotel foo lemon coffee}
...
position y : {}
How can I improve the efficiency of this function?