Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to find the first repeating element in an array of integers with Java

1 Answer

0 votes
import java.util.*; 

public class MyClass {
    public static int get_first_repeating_element(int arr[]) { 
        int x = -1; 
        HashSet<Integer> set = new HashSet<>(); 
       
        for (int i = arr.length-1; i >= 0; i--) {
            if (set.contains(arr[i]))
                x = i; 
            else  
                set.add(arr[i]); 
        } 
       
        if (x != -1) 
            return arr[x]; 
         
        return -1;
    } 
    public static void main(String args[]) {
        int arr[] = {1, 2, 4, 5, 6, 5, 4, 3, 7}; 
   
        int n = get_first_repeating_element(arr); 
     
        if (n != -1) 
            System.out.println("First repeating element is: " + n); 
        else
            System.out.println("No repeating elements"); 
    }
}



/*
run:

First repeating element is: 4

*/

 



answered May 13, 2019 by avibootz
...