laredotornado said:
I have an array of Calendar objects. How can I tell if any of the
object's values in the array occurs more than once (e.g. two objects
with values "01-01-1999 9:00 AM")? If it is easier, I can convert the
Calendar[] array to some other type of collection.
Heh, it's been a long time since I've seen this interview question. I have a
secret hope that it's a real problem, but it seems unlikely.
I'm going to assume that you care about millisecond precision, but do not care
about what non-Date data (like timezone) the Calendar contains. Thus, I'll
compare the getTimeInMillis() rather than just using .equals() or doing
something more complicated to truncate to minutes as your example shows.
Peter Duniho said:
The usual "most-efficient" approach would be to sort the data and then
look for consecutive duplicates.
That's most efficient only if you don't want to allocate additional space.
If you don't mind having a separate data structure, it's more efficient
to build a hash as you check for duplicates.
O(n) for a hash-based solution, O(n * logn) for the sort.
A less efficient alternative is to examine each element and search the
array for a duplicate. But that's O(n^2) instead of O(n log n). You'd
only want to do it that way if your collection is extremely small or for
some reason sorting (optionally copying before) the data was impossible.
Build the search as you go. something like:
Map<Long, Calendar> calendars = new HashMap<Long, Calendar>();
for (Calendar c : calendarArray) {
long calValue = c.getTimeInMillis();
if (calendars.containsKey(calValue)) {
// you have a duplicate! Do whatever you must!
}
calendars.put(calValue, c);
}