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:
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top