📜  重建队列后找到两个人之间的距离

📅  最后修改于: 2021-05-04 19:10:32             🧑  作者: Mango

给定大小为N的2D数组,其中包含排在队列中的人员的不同身高,以及一个对应于每个人(P)的数字,该数字给出了小于P且位于P前面的人数。两个人AB之间的距离按人的身高的实际顺序排列。

例子:

天真的方法:蛮力方法是尝试对菲尼克斯成员的阶的给定高度进行所有可能的排列,并验证前面的数字是否与给定序列匹配,然后找出两个人之间的距离。
时间复杂度: O(N!)

高效方法:另一种方法是存储人的身高及其前值,将其存储在任何向量中,然后根据身高按升序对向量进行排序。现在,遍历向量并将该人插入位置向量中的第k个位置,其中k是站在当前人的人前面的人的数量。

下面是上述方法的实现:

CPP
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to find the correct order and then
// return the distance between the two persons
int getDistance(int arr[][2], int n, int a, int b)
{
    vector > vp;
  
    // Make pair of both height & infront
    // and insert to vector
    for (int i = 0; i < n; i++) {
        vp.push_back({ arr[i][0], arr[i][1] });
    }
  
    // Sort the vector in ascending order
    sort(vp.begin(), vp.end());
  
    // Find the correct place for every person
    vector pos;
  
    // Insert into postion vector
    // according to infront value
    for (int i = 0; i < vp.size(); i++) {
        int height = vp[i].first;
        int k = vp[i].second;
        pos.insert(pos.begin() + k, height);
    }
  
    int first = -1, second = -1;
  
    for (int i = 0; i < pos.size(); i++) {
        if (pos[i] == a)
            first = i;
        if (pos[i] == b)
            second = i;
    }
  
    return abs(first - second);
}
  
// Driver code
int main()
{
    int arr[][2] = {
        { 5, 0 },
        { 3, 0 },
        { 2, 0 },
        { 6, 4 },
        { 1, 0 },
        { 4, 3 }
    };
    int n = sizeof(arr) / sizeof(arr[0]);
    int a = 6, b = 5;
  
    cout << getDistance(arr, n, a, b);
  
    return 0;
}


Python
# Python implementation of the approach
  
# Function to find the correct order and then
# return the distance between the two persons
def getDistance(arr, n, a, b):
    vp = []
  
    # Make pair of both height & infront
    # and insert to vector
    for i in range(n):
        vp.append([arr[i][0], arr[i][1]])
  
    # Sort the vector in ascending order
    vp = sorted(vp)
  
    # Find the correct place for every person
    pos = [0 for i in range(n)]
  
    # Insert into postion vector
    # according to infront value
    for i in range(len(vp)):
        height = vp[i][0]
        k = vp[i][1]
        pos[k] = height
  
    first = -1
    second = -1
  
    for i in range(n):
        if (pos[i] == a):
            first = i
        if (pos[i] == b):
            second = i
  
    return abs(first - second)
  
# Driver code
arr = [[5, 0],
        [3, 0],
        [2, 0],
        [6, 4],
        [1, 0],
        [4, 3]]
n = len(arr)
a = 6
b = 5
  
print(getDistance(arr, n, a, b))
  
# This code is contributed by mohit kumar 29


输出:
4

时间复杂度: O(n 2 )