If I were to implement a code that searchs for the first repeating pair in an array, this code would return the index of the first repeating pair. Using arrays and not array lists or sets.
for example; a=[1,2,3,4,2,1]; This code would return the index of the second 2 that was repeating. Output= 4. Please help
public class lib{
public static void main(String[] args){
int a[]={1,2,3,4,2,1};
int pair[]=new int[2];
boolean flag=false;
for(int i=0;i<a.length-1;i++){
pair[0]=a[i];
pair[1]=a[i+1];
for(int j=i+1;j<a.length-1;j++){
if((a[j]==pair[0]&&a[j+1]==pair[1])||(a[j]==pair[1]&&a[j+1]==pair[0])){
System.out.println("index of first repeating pair : "+j);
flag=true;
break;
}
}
if(flag==true)break;
}
}
}
Get Answers For Free
Most questions answered within 1 hours.