2. Value equal to index value
2. Value equal to index value
Problem link :- click here
package program;
import java.util.ArrayList;
import java.util.List;
public class Searching__2
{
/*
Given an array arr[] of n positive integers. Our task is to find the elements
whose value is equal to that of its index value.
n = 5 arr[] = {15, 2, 45, 12, 7}
output : 2
lets iterate through the array and add all the elements that are equal to their
indices to a ArrayList and return the array list
*/
static List<Integer> valueEqualToIndex(int arr[], int n)
{
List<Integer> result = new ArrayList<>();
for(int i=0; i<n; i++)
{
if(arr[i] == i+1)
result.add(arr[i]);
}
return result;
}
public static void main(String[] args)
{
int arr[] = {1, 2, 45, 4, 7};
List<Integer> ans = valueEqualToIndex(arr, arr.length);
System.out.println("Elements whose values are equal to indices are : \n\t\t" + ans);
}
}
Time complexity :- O(n)
Space complexity :- O(1)
Comments
Post a Comment