Find Last occurrence index of given number from array

Write a program to find the last occurrence index of a given number from an array.

Example 1:

Input: arr= [1,2,1], targer=1
Output: index = 2

Approach

Java

public class LastOccurrenceArrayIndex {
    public static void main(String[] args) {
        int arr[] = { 121 };
        int target = 3;
        int index = findLastOccurence(arr, target);
        System.out.println("Last Occurrence is " + index);
    }

    private static int findLastOccurence(int[] arrint target) {
        int l = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                l = i;
            }
        }
        return l;
    }
}

// Time Complexity: O(n)
// Space Complexity: O(1)

C++

#include <bits/stdc++.h>
using namespace std;
//Function to find last occurrence
//of given number
int lastOccurrence(int arr[],int n,int target)
{
    int index=-1;
    for(int i=0;i<n;i++)
      {
          if(arr[i]==target)
            {
                index=i;
            }
      }
     return index;
}
int main()
{
    int arr[]={1,2,1};
    int target=1;
    int n=sizeof(arr)/sizeof(arr[0]);
    int index=lastOccurrence(arr,n,target);
    cout<<"Last Occurrence is "<<index;
    return 0;
}
//Time Complexity: O(n)
//Space Complexity:O(1)


No comments:

Post a Comment