Find First and Last Index of a Number
public class FirstAndLastIndedOfNumber { public static void main(String[] args) { int arr[] = {1, 2, 2, 3, 4, 5, 3, 2, 7, 22, 22}; int first = -1; int last = -1; boolean flag = true; int searchNumber = 2; for(int i=0; i<arr.length; i++){ if(searchNumber == arr[i]){ if(flag){ first = i; flag = false; } last = i; } } System.out.println(first + "\t" + last); } }
Comments
Post a Comment