The goal is to have no duplicates in my Arraylist of Arraylist of Integers "listResults". Here I iterate through a list of elements "listOfElements", and if the sum of two elements within this list is equal to the target, then I store indexes of both elements in an ArrayList "pair". Then I add that ArrayList to the list of ArrayList "listResults" and continue iterating. At the end I might end up with listResults containing one or more arrayLists. However I don't want it to contain duplicates like [2,3] and [3,2] or [4,0] and [0,4]
int target = 60;
ArrayList<ArrayList<Integer>> listResults = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> listOfElements = new ArrayList<Integer>();
listOfElements.add(1);
listOfElements.add(10);
listOfElements.add(25);
listOfElements.add(35);
listOfElements.add(60);
for (int i = 0; i < listOfElements.size(); i++) {
for (int j = 0; j < listOfElements.size(); j++) {
if (listOfElements.get(i) + listOfElements.get(j) == target) {
ArrayList<Integer> pair = new ArrayList<Integer>();
pair.add(i);
pair.add(j);
listResults.add(pair);
}
}
}
System.out.println(listResults);
Based on the current code, the output is: [ [2,3] , [3,2] ] but this is not acceptable as [2,3] and [3,2] are duplicates. Only [2,3] should be allowed as it was the first one to be added to the ArrayList.
You shouldn't check the already visited elements. In your inner for-loop,
change
int j = 0;
to
int j = i + 1;
如果条件为真,请使用break语句。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.