The algorithm only need to detect if there are at least 2 number which are the same.
Is the one in my picture the best way to do it or is there a more effective way.
This is a task in a book and I don't no if i did it right.
Algorithm
The algorithm only need to detect if there are at least 2 number which are the same.
Is the one in my picture the best way to do it or is there a more effective way.
This is a task in a book and I don't no if i did it right.
Algorithm
If the array is sorted:
for(int i=0; i<a.length-1; i++)
if(a[i]==a[i+1])
return true;
return false;
if the array is not sorted, use a cache:
boolean[] cache=new boolean[N];
Arrays.fill(cache,false); //set all values to false
for(int i=0; i<a.length; i++)
if(cache[a[i]])
return true;
else
cache[a[i]]=true; //mark element a[i] as seen
return false;
In the above, N is the maximum value that occurs in array a. If N is unknown or very large, or your array contains negative values, use a map instead of an array as cache.
Both solutions run in O(n) time. The second solution just needs an external cache to remember which elements we've seen before.