📜  在 K 从给定数组的开头跳转后查找位置,其中每次跳转都是从 i 到 arr[i]

📅  最后修改于: 2022-05-13 01:57:48.522000             🧑  作者: Mango

在 K 从给定数组的开头跳转后查找位置,其中每次跳转都是从 i 到 arr[i]

给定一个大小为N的数组arr[]包含从1 到 N的元素。找到恰好K从索引 1 跳转后的位置,从第 i 个索引的跳转发送到 arr[i] 索引。

例子:

方法:这个问题可以使用地图数据结构来解决。动机是找到从一个元素跳转到另一个元素时形成的循环。当观察到循环或循环时,标记它已访问并计算重复此位置所采取的跳转次数,并使用 map 将其存储在 X 中,如果再次访问,则下一个 X 跳转是相同的。所以从 K = K % X 取模。

  • 初始化地图
  • 初始化一个变量len = 0idx = 1
  • 进行一个while循环并运行直到K的值大于0或检测到循环。
  • 循环结束后,从 K 中减去循环len
  • 现在,进行剩余的跳跃。

下面是上述方法的实现。

C++
// C++ code to implement above approach
#include 
using namespace std;
 
// Function to determine the position
int LastElement(int arr[], int N, int K)
{
    // Decrement all array values by 1
    // so it is easy to jump
    for (int i = 0; i < N; i++) {
        --arr[i];
    }
     
    // Initialize the unordered Map
    unordered_map visit;
     
    // Initialize elem and len
    int elem = 0, len = 0;
     
   // Traverse until K is not 0
    //or loop is detected
    while (K and !visit[elem]) {
         
        // Store len in map
        visit[elem] = ++len;
         
        // Decrement K for a jump
        K--;
         
        // Jump from one element to another
        elem = arr[elem];
    }
 
    // After loop is over, take modulo of K
    K = K % (len + 1 - visit[elem]);
 
    // Now traverse loop K times
    for (int i = 1; i <= K; i++) {
        elem = arr[elem];
    }
    // Lastly return the element
    return elem + 1;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 2, 4, 1 };
    int N = 4;
    int K = 5;
    int ans = LastElement(arr, N, K);
    cout << ans;
    return 0;
}


Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
   
  // Function to determine the position
  static int LastElement(int arr[], int N, int K)
  {
     
    // Decrement all array values by 1
    // so it is easy to jump
    for (int i = 0; i < N; i++) {
      --arr[i];
    }
 
    // Initialize the Map
    HashMap visit = new HashMap();
     
    // Initialize elem and len
    int elem = 0, len = 0;
 
    // Traverse until K is not 0
    //or loop is detected
    while (K >= 0 && visit.get(elem) == null)
    {
 
      // Store len in map
      visit.put(elem, ++len);
 
      // Decrement K for a jump
      K--;
 
      // Jump from one element to another
      elem = arr[elem];
    }
 
    // After loop is over, take modulo of K
    K = K % (len + 1 - visit.get(elem));
 
    // Now traverse loop K times
    for (int i = 1; i <= K; i++) {
      elem = arr[elem];
    }
     
    // Lastly return the element
    return elem + 1;
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int arr[ ] = { 3, 2, 4, 1 };
    int N = 4;
    int K = 5;
    int ans = LastElement(arr, N, K);
    System.out.print(ans);
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3
# Python code for the above approach
 
# Function to determine the position
def LastElement(arr, N, K) :
 
    # Decrement all array values by 1
    # so it is easy to jump
    for i in range(N):
        arr[i] -= 1
 
    # Initialize the unordered Map
    visit = [0] * (N);
 
    # Initialize elem and len
    elem = 0
    _len = 0;
 
    # Traverse until K is not 0
    #or loop is detected
    while (K and not visit[elem]):
 
        # Store len in map
        visit[elem] = ++_len;
 
        # Decrement K for a jump
        K -= 1
 
        # Jump from one element to another
        elem = arr[elem];
 
 
    # After loop is over, take modulo of K
    K = K % (_len + 1 - visit[elem]);
 
    # Now traverse loop K times
    for i in range(1, K + 1):
        elem = arr[elem];
    # Lastly return the element
    return elem + 1;
 
# Driver code
arr = [3, 2, 4, 1];
N = 4;
K = 5;
ans = LastElement(arr, N, K);
print(ans);
 
# This code is contributed by Saurabh jaiswal


C#
/*package whatever //do not write package name here */
using System;
using System.Collections.Generic;
public class GFG {
 
  // Function to determine the position
  static int LastElement(int []arr, int N, int K)
  {
 
    // Decrement all array values by 1
    // so it is easy to jump
    for (int i = 0; i < N; i++) {
      --arr[i];
    }
 
    // Initialize the Map
    Dictionary visit = new Dictionary();
 
    // Initialize elem and len
    int elem = 0, len = 0;
 
    // Traverse until K is not 0
    //or loop is detected
    while (K >= 0 && !visit.ContainsKey(elem))
    {
 
      // Store len in map
      visit.Add(elem, ++len);
 
      // Decrement K for a jump
      K--;
 
      // Jump from one element to another
      elem = arr[elem];
    }
 
    // After loop is over, take modulo of K
    K = K % (len + 1 - visit[elem]);
 
    // Now traverse loop K times
    for (int i = 1; i <= K; i++) {
      elem = arr[elem];
    }
 
    // Lastly return the element
    return elem + 1;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int []arr = { 3, 2, 4, 1 };
    int N = 4;
    int K = 5;
    int ans = LastElement(arr, N, K);
    Console.Write(ans);
  }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
4

时间复杂度: O(N)
辅助空间: O(N)