Find the Last Occurrence of an Element
Get an
array of Integers arr[] with size n and element e to be found. Apply Linear Search / Binary Search to find the
element e’s last occurrence position in the array arr[]. If element e is found, print its last occurred index; if not
found, print -1.
Examples
Input
1:
5
5
7 9 3 9
9
Output
1:
4
Input
2:
5
5
7 9 3 1
4
Output
2:
-1
Input
3:
5
5
7 9 3 1
9
Output
3:
2
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class SearchLO
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n,e,pos=-1;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
e = input.nextInt();
//Linear Search
for(int i = n-1; i>=0; i--)
{
if(arr[i]==e)
{
pos = i;
break;
}
}
System.out.print(pos);
}
}