Retrieve all value pairs from List<Integer>
For example I have a List<Integer>
object with the following:
3, 6, 5, 3, 3, 6
The result would be 3 and 6. How can I create a function that tests for duplicates and then returns 1 value of the duplicate (not the pair, just one in the pair)? One problem that mig开发者_StackOverflow社区ht occur is if there are quadruple values: 3, 4, 5, 3, 8, 3, 3
Then I would like to return 3 and 3. How can I accomplish this?
I would go through the list counting the number of instances of each one (storing them in a map) and then create a new list from the map:
List<Integer> values = // the list of values you have
Map<Integer,Integer> counts = new HashMap<Integer,Integer>();
for(Integer value : values) {
if(counts.containsKey(value)) {
counts.put(value, counts.get(value)+1);
} else {
counts.put(value, 1);
}
}
List<Integer> resultValues = new ArrayList<Integer>();
for(Integer value : counts.keySet()) {
Integer valueCount = counts.get(value);
for(int i=0; i<(valueCount/2); i++) { //add one instance for each 2
resultValues.add(value);
}
}
return resultValues;
This avoids the O(nlogn) behavior of sorting the values first, working in O(n) instead.
I think the "map" way by @RHSeeger is good enough. Here I just suggest another way, just for 'fun', so that u may take a look. It kind of give a stable result: first completed pairs appears first:
List<Integer> values = ....;
List<Integer> result = new ArrayList<Integer>();
Set<Integer> unpairedValues = new HashSet<Integer>();
for (int i : values) {
if (unpairedValues.contains(i)) {
result.add(i);
unpairedValues.remove(i);
} else {
unpairedValues.add(i);
}
}
// result contains what u want
One possible way in pseudo code:
sortedList = sort (list)
duplicates = empty list
while (length (list) > 1)
{
if (list [0] == list [1] )
{
duplicates.append (list [0] )
list.removeAt (0)
}
list.removeAt (0);
}
// ArrayList<Integer> list = {3, 6, 5, 3, 3, 6}
Collections.sort(list);
ArrayList<Integer> pairs = new ArrayList<Integer>();
int last = Integer.MIN_VALUE; // some value that will never appear in the list
for (Integer cur : list) {
if (last == cur) {
pairs.add(cur);
last = Integer.MIN_VALUE; // some value that will never appear in the list
} else {
last = cur;
}
}
System.out.println(Arrays.toString(pairs.toArray()));
Will output
[3, 6]
** Edit **
Slightly better algorithm, modifies the given list
// ArrayList<Integer> list = {3, 6, 5, 3, 3, 6}
Collections.sort(list);
int index = 1, last;
while (index < list.size()) {
last = list.remove(index - 1);
if (list.get(index - 1) == last) {
index++;
}
if (index == list.size()) {
list.remove(index - 1);
}
}
精彩评论