How to search for duplicate values in an array of integers?

AI Thread Summary
To find duplicate values in a sorted array of integers in Java, a straightforward approach involves iterating through the array and comparing each element with the previous one. The suggested method checks if the current element is equal to the next, returning true if a duplicate is found. This efficient technique leverages the sorted nature of the array, allowing for a simple linear scan to identify duplicates. The provided code snippet demonstrates this method effectively.
pumas
Messages
15
Reaction score
0
I'm trying to search for duplicate values in a array of integers in Java. The array of intergers is sorted. Could anyone give me an idea on how to get started. :confused:
 
Technology news on Phys.org
If its sorted then it's pretty easy, just walk through the array checking if each value is the same as the previous one.
 
Something like this:
Code:
boolean has_duplicate (int[] arr) {
  int lim = arr.length - 1;
  for (int i = 0; i < lim;)
    if (arr[i] == arr[++i])
      return true;
  return false;
}
 
Thank you for your help :smile:
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top