0

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

enter image description here

Nemus
  • 3,879
  • 12
  • 38
  • 57

2 Answers2

2

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.

Joris Kinable
  • 2,232
  • 18
  • 29
0

Can you just do:

Loop on I
      Loop on j
             If value of a[I] = value of a[j]
                   Break;  /*at least one double found*/

No?

Wrong.. Forget about it..

Totoc1001
  • 338
  • 2
  • 11