给定一个大小为N的数组arr[] ,任务是找到最大索引i使得arr[i]等于i。如果数组arr[] 中没有这样的索引,则打印-1 。
例子:
Input: arr[ ] = {-10, -5, 0, 3, 7}
Output: 3
Explanation: Only for i=3, arr[3] = 3
Input: arr[ ] = {0, 2, 5, 8, 4}
Output: 4
方法:按照以下步骤解决此问题:
- 使用变量i在范围[N-1, 0] 中迭代:
- 如果当前元素等于i ,则打印i并返回。
- 如果没有这样的索引,则打印-1。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find the maximum index
// i such that arr[i] is equal to i
void findLargestIndex(int arr[], int n)
{
// Traversing the array from
// backwards
for (int i = n - 1; i >= 0; i--) {
// If arr[i] is equal to i
if (arr[i] == i) {
cout << i << endl;
return;
}
}
// If there is no such index
cout << -1 << endl;
}
// Driver code
int main()
{
// Given Input
int arr[] = { -10, -5, 0, 3, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
findLargestIndex(arr, n);
return 0;
}
Java
// Java implementation of the above approach
import java.io.*;
class GFG
{
// Function to find the maximum index
// i such that arr[i] is equal to i
static void findLargestIndex(int arr[], int n)
{
// Traversing the array from
// backwards
for (int i = n - 1; i >= 0; i--) {
// If arr[i] is equal to i
if (arr[i] == i) {
System.out.println(i);
return;
}
}
// If there is no such index
System.out.println(-1);
}
// Driver code
public static void main(String[] args)
{
// Given Input
int arr[] = { -10, -5, 0, 3, 7 };
int n = arr.length;
// Function Call
findLargestIndex(arr, n);
}
}
// This code is contributed by Potta Lokesh
Python
# Python implementation of the above approach
# Function to find the maximum index
# i such that arr[i] is equal to i
def findLargestIndex(arr, n):
# Traversing the array from
# backwards
for i in range (n):
# If arr[i] is equal to i
if (arr[i] == i) :
print( i )
return
# If there is no such index
print( -1 )
# Driver code
# Given Input
arr = [-10, -5, 0, 3, 7 ]
n = len(arr)
# Function Call
findLargestIndex(arr, n)
# This code is contributed by shivanisinghss2110
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to find the maximum index
// i such that arr[i] is equal to i
static void findLargestIndex(int []arr, int n)
{
// Traversing the array from
// backwards
for (int i = n - 1; i >= 0; i--) {
// If arr[i] is equal to i
if (arr[i] == i) {
Console.Write(i);
return;
}
}
// If there is no such index
Console.Write(-1);
}
// Driver code
public static void Main(String[] args)
{
// Given Input
int []arr = { -10, -5, 0, 3, 7 };
int n = arr.Length;
// Function Call
findLargestIndex(arr, n);
}
}
// This code is contributed by shivanisinghss2110
Javascript
输出
3
时间复杂度:O(N)
辅助空间:O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。