给定一个整数K和一个长度为N的索引数组arr [] ,其中包含范围为[1,N]的元素,任务是从索引1开始以K个步长遍历该数组后查找索引。
遍历索引数组:在遍历索引数组时,下一个要访问的索引是当前索引处的值。
例子:
Input: arr[] = {3, 2, 4, 1}, K = 5
Output: 4
Explanation:
Traversal to the indices starting from index 1:
1 => 3 => 4 => 1 => 3 => 4
Finally, after K traversals the index is 4
Input: arr[] = {6, 5, 2, 5, 3, 2}, K = 2
Output: 5
方法:该问题的主要观察结果是在遍历索引数组N次之后,它会重复自身。因此,我们可以找到然后最后找到索引遍历。
下面是上述方法的实现:
C++
// C++ implementation to find the
// index after traversing the index
// array K times
#include
using namespace std;
// Function to find the index after
// traversing the index array K times
int findIndexAfterKTrav(vector arr,
int n, int k){
k = k % n;
int indi = 1;
// Loop to traverse the index
// array K times
while (k){
indi = arr[indi-1];
k--;
}
return arr[indi-1];
}
// Driver Code
int main() {
int n = 4, k = 5;
vector arr{3, 2, 4, 1};
// Function Call
cout << findIndexAfterKTrav(arr, n, k);
return 0;
}
Java
// Java implementation to find the
// index after traversing the index
// array K times
class GFG{
// Function to find the index after
// traversing the index array K times
public static int findIndexAfterKTrav(int[] arr,
int n, int k)
{
k = k % n;
int indi = 1;
// Loop to traverse the index
// array K times
while (k > 0)
{
indi = arr[indi - 1];
k--;
}
return arr[indi - 1];
}
// Driver code
public static void main(String[] args)
{
int n = 4, k = 5;
int[] arr = { 3, 2, 4, 1 };
// Function Call
System.out.print(findIndexAfterKTrav(arr, n, k));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 implementation to find the
# index after traversing the index
# array K times
# Function to find the index after
# traversing the index array K times
def findIndexAfterKTrav(arr, n, k):
k = k % n;
indi = 1;
# Loop to traverse the index
# array K times
while (k > 0):
indi = arr[indi - 1];
k -= 1;
return arr[indi - 1];
# Driver code
if __name__ == '__main__':
n = 4;
k = 5;
arr = [ 3, 2, 4, 1 ];
# Function Call
print(findIndexAfterKTrav(arr, n, k));
# This code is contributed by Princi Singh
C#
// C# implementation to find the
// index after traversing the index
// array K times
using System;
class GFG{
// Function to find the index after
// traversing the index array K times
public static int findIndexAfterKTrav(int[] arr,
int n, int k)
{
k = k % n;
int indi = 1;
// Loop to traverse the index
// array K times
while (k > 0)
{
indi = arr[indi - 1];
k--;
}
return arr[indi - 1];
}
// Driver code
public static void Main(String[] args)
{
int n = 4, k = 5;
int[] arr = { 3, 2, 4, 1 };
// Function Call
Console.Write(findIndexAfterKTrav(arr, n, k));
}
}
// This code is contributed by Princi Singh
输出:
4