Created
June 14, 2017 05:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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