Reputation: 698
What is the easiest/simplest/most efficient way to detect if a 2D array has duplicate/repeating values?
e.g. 2D Array:
{{2, 17, 4, 5} {3, 2, 34 9}}
This matrix has multiple "2" values.
I want to set a boolean to true if this is the case.
Thanks in advance!
Upvotes: 1
Views: 1127
Reputation: 67370
I think the best you can do here is O(n) because you won't know if the very last element is a duplicate until you check it. Here's an idea:
Have a Set
of values. Iterate the 2d array and for each element do this:
if (!set.add(element))
// a duplicate was found!
This works because Set.add returns "true if this set did not already contain the specified element"
Upvotes: 3