Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 14, 2017 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/1a4fc24a2960b2170f4604cc9a8a67de to your computer and use it in GitHub Desktop.
Save anil477/1a4fc24a2960b2170f4604cc9a8a67de to your computer and use it in GitHub Desktop.
Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest.
// http://www.geeksforgeeks.org/find-first-repeating-element-array-integers/
import java.io.*;
import java.util.*;
class FirstRepeating
{
void printMajority(int a[], int n)
{
Set<Integer> set = new HashSet<Integer>();
int majority = -1;
for (int i = 0; i < n; i++){
if (set.contains(a[i])) {
majority = i;
} else {
set.add(a[i]);
}
}
System.out.println(a[majority]);
}
// Driver program to test above functions
public static void main(String[] args)
{
FirstRepeating obj = new FirstRepeating();
int arr[] = {10, 5, 3, 4, 3, 5, 6, 10};
int n = arr.length;
obj.printMajority(arr, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment