To find the first repeating element in an array of integers, you can use a HashSet to keep track of the elements you have encountered so far. Here's a Java implementation:
import java.util.HashSet;
public class FirstRepeatingElement {
public static int findFirstRepeating(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) {
return num;
}
set.add(num);
}
return -1; // If no repeating element is found
}
public static void main(String[] args) {
int[] nums = {3, 2, 1, 2, 2, 3};
int firstRepeating = findFirstRepeating(nums);
if (firstRepeating != -1) {
System.out.println("First repeating element: " + firstRepeating); // Output: 3
} else {
System.out.println("No repeating element found.");
}
}
}
In this implementation:
- We use a HashSet to keep track of the elements encountered so far.
- We iterate through the array and check if each element is already present in the HashSet.
- If an element is found to be already present, it is the first repeating element, so we return it.
- If no repeating element is found, we return -1.
- We test the implementation with an example array and print the first repeating element, if found. Otherwise, we print a message indicating that no repeating element is found.