📌  相关文章
📜  对数轴上的数字进行排序所需的最小跳跃次数

📅  最后修改于: 2021-10-27 09:18:03             🧑  作者: Mango

给定两个由N 个正整数组成的数组W[]L[] ,其中W[i]最初位于无限数轴上的位置i 。在每次向前跳跃时, W[i]可以从其当前位置j跳到位置(j + L[i])到任何空位置。任务是找到对数组进行排序所需的最小向前跳转次数。

例子:

方法:给定的问题可以通过使用贪婪方法来解决,方法是最小化数组中每个操作中没有正确定位的最小元素所需的跳转次数,并更新跳转次数。请按照以下步骤解决问题:

方法:给定的问题可以通过使用贪婪方法来解决,方法是最小化数组中每个操作中没有正确定位的最小元素所需的跳转次数,并更新跳转次数。请按照以下步骤解决问题:

  • 初始化一个变量,比如ans0来存储所需的最小跳转次数。
  • 创建数组W[]的副本并将元素按排序顺序存储在数组arr[] 中
  • 初始化一个 HashMap pos来存储元素W[i]的当前位置。
  • 遍历数组W[]并更新W[i]pos 中的位置
  • 遍历[1,N-1]范围内的数组arr[ ] ,执行以下步骤:
    • 将数组W[]arr[i]的位置和arr[i – 1]的位置存储在变量中,分别是currprev
    • 如果curr的值大于prev ,则继续下一次迭代。
    • 否则,迭代直到curr ≤ prevcurr已被占用并通过跳转增加curr的值并将ans的值增加1
    • arr[i]在 HashMap pos 中的位置更新为curr
  • 完成以上步骤后,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum number
// of jumps required to sort the array
void minJumps(int w[], int l[], int n)
{
    // Base Case
    if (n == 1) {
        cout << 0;
        return;
    }
 
    // Store the required result
    int ans = 0;
 
    // Stores the current position of
    // elements and their respective
    // maximum jump
    unordered_map pos, jump;
 
    // Used to check if a position is
    // already taken by another element
    unordered_map filled;
 
    // Stores the sorted array a[]
    int a[n];
 
    // Traverse the array w[] & update
    // positions jumps array a[]
    for (int i = 0; i < n; i++) {
 
        pos[w[i]] = i;
        filled[i] = true;
        jump[w[i]] = l[i];
        a[i] = w[i];
    }
 
    // Sort the array a[]
    sort(a, a + n);
 
    // Traverse the array a[] over
    // the range [1, N-1]
    for (int curr = 1;
         curr < n; curr++) {
 
        // Store the index of current
        // element and its just smaller
        // element in array w[]
        int currElementPos
            = pos[a[curr]];
        int prevElementPos
            = pos[a[curr - 1]];
 
        if (currElementPos
            > prevElementPos)
            continue;
 
        // Iterate until current element
        // position is at most its just
        // smaller element position
        while (currElementPos
                   <= prevElementPos
               || filled[currElementPos]) {
 
            currElementPos += jump[a[curr]];
            ans++;
        }
 
        // Update the position of the
        // current element
        pos[a[curr]] = currElementPos;
        filled[currElementPos] = true;
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    int W[] = { 2, 1, 4, 3 };
    int L[] = { 4, 1, 2, 4 };
    int N = sizeof(W) / sizeof(W[0]);
    minJumps(W, L, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG {
 
    // Function to find the minimum number
    // of jumps required to sort the array
    static void minJumps(int[] w, int[] l, int n)
    {
 
        // Base Case
        if (n == 1) {
            System.out.print(0);
            return;
        }
 
        // Store the required result
        int ans = 0;
 
        // Stores the current position of
        // elements and their respective
        // maximum jump
        HashMap pos
            = new HashMap();
        HashMap jump
            = new HashMap();
 
        // Used to check if a position is
        // already taken by another element
        HashMap filled
            = new HashMap();
 
        // Stores the sorted array a[]
        int[] a = new int[n];
 
        // Traverse the array w[] & update
        // positions jumps array a[]
        for (int i = 0; i < n; i++) {
            if (pos.containsKey(w[i]))
                pos.put(w[i], i);
            else
                pos.put(w[i], i);
            if (filled.containsKey(w[i]))
                filled.put(i, true);
            else
                filled.put(i, true);
            if (jump.containsKey(w[i]))
                jump.put(w[i], l[i]);
            else
                jump.put(w[i], l[i]);
 
            a[i] = w[i];
        }
 
        // Sort the array a[]
        Arrays.sort(a);
 
        // Traverse the array a[] over
        // the range [1, N-1]
        for (int curr = 1; curr < n; curr++) {
 
            // Store the index of current
            // element and its just smaller
            // element in array w[]
            int currElementPos = pos.get(a[curr]);
            int prevElementPos = pos.get(a[curr - 1]);
 
            if (currElementPos > prevElementPos)
                continue;
 
            // Iterate until current element
            // position is at most its just
            // smaller element position
            while (currElementPos <= prevElementPos
                   || filled.containsKey(currElementPos)
                          && filled.containsKey(
                              currElementPos)) {
                currElementPos += jump.get(a[curr]);
                ans++;
            }
 
            // Update the position of the
            // current element
            if (pos.containsKey(a[curr]))
                pos.put(a[curr], currElementPos);
            else
                pos.put(a[curr], currElementPos);
            if (filled.containsKey(currElementPos))
                filled.put(currElementPos, true);
            else
                filled.put(currElementPos, true);
        }
 
        // Print the result
        System.out.print(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] W = { 2, 1, 4, 3 };
        int[] L = { 4, 1, 2, 4 };
        int N = W.length;
 
        minJumps(W, L, N);
    }
}
 
// This code is contributed by ukasp.


Python3
# Python3 program for the above approach
 
# Function to find the minimum number
# of jumps required to sort the array
def minJumps(w, l, n):
     
    # Base Case
    if (n == 1):
        print(0)
        return
 
    # Store the required result
    ans = 0
 
    # Stores the current position of
    # elements and their respective
    # maximum jump
    pos = {}
    jump = {}
 
    # Used to check if a position is
    # already taken by another element
    filled = {}
 
    # Stores the sorted array a[]
    a = [0 for i in range(n)]
 
    # Traverse the array w[] & update
    # positions jumps array a[]
    for i in range(n):
        pos[w[i]] = i
        filled[i] = True
        jump[w[i]] = l[i]
        a[i] = w[i]
 
    # Sort the array a[]
    a.sort()
 
    # Traverse the array a[] over
    # the range [1, N-1]
    for curr in range(1, n, 1):
         
        # Store the index of current
        # element and its just smaller
        # element in array w[]
        currElementPos = pos[a[curr]]
        prevElementPos = pos[a[curr - 1]]
 
        if (currElementPos > prevElementPos):
            continue
 
        # Iterate until current element
        # position is at most its just
        # smaller element position
        while (currElementPos <= prevElementPos or
              (currElementPos in filled and
              filled[currElementPos])):
            currElementPos += jump[a[curr]]
            ans += 1
 
        # Update the position of the
        # current element
        pos[a[curr]] = currElementPos
        filled[currElementPos] = True
 
    # Print the result
    print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    W = [ 2, 1, 4, 3 ]
    L = [ 4, 1, 2, 4 ]
    N = len(W)
     
    minJumps(W, L, N)
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum number
// of jumps required to sort the array
static void minJumps(int []w, int []l, int n)
{
     
    // Base Case
    if (n == 1)
    {
        Console.Write(0);
        return;
    }
 
    // Store the required result
    int ans = 0;
 
    // Stores the current position of
    // elements and their respective
    // maximum jump
    Dictionary pos = new Dictionary();
    Dictionary jump = new Dictionary();
 
    // Used to check if a position is
    // already taken by another element
     Dictionary filled = new Dictionary();
 
    // Stores the sorted array a[]
    int []a = new int[n];
 
    // Traverse the array w[] & update
    // positions jumps array a[]
    for(int i = 0; i < n; i++)
    {
        if (pos.ContainsKey(w[i]))
           pos[w[i]] = i;
        else
           pos.Add(w[i], i);
        if (filled.ContainsKey(w[i]))
           filled[i] = true;
        else
           filled.Add(i, true);
        if (jump.ContainsKey(w[i]))
           jump[w[i]] = l[i];
        else
           jump.Add(w[i], l[i]);
            
        a[i] = w[i];
    }
 
    // Sort the array a[]
    Array.Sort(a);
 
    // Traverse the array a[] over
    // the range [1, N-1]
    for(int curr = 1; curr < n; curr++)
    {
         
        // Store the index of current
        // element and its just smaller
        // element in array w[]
        int currElementPos = pos[a[curr]];
        int prevElementPos = pos[a[curr - 1]];
 
        if (currElementPos > prevElementPos)
            continue;
 
        // Iterate until current element
        // position is at most its just
        // smaller element position
        while (currElementPos <= prevElementPos ||
               filled.ContainsKey(currElementPos) &&
               filled[currElementPos])
        {
            currElementPos += jump[a[curr]];
            ans++;
        }
         
        // Update the position of the
        // current element
        if (pos.ContainsKey(a[curr]))
            pos[a[curr]] = currElementPos;
        else
            pos.Add(a[curr], currElementPos);
        if (filled.ContainsKey(currElementPos))
            filled[currElementPos] = true;
        else
            filled.Add(currElementPos, true);
    }
 
    // Print the result
    Console.Write(ans);
}
 
// Driver Code
public static void Main()
{
    int []W = { 2, 1, 4, 3 };
    int []L = { 4, 1, 2, 4 };
    int N = W.Length;
     
    minJumps(W, L, N);
}
}
 
// This code is contributed by ipg2016107


Javascript


输出:
5

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程