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

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.