📌  相关文章
📜  查询以查找给定数组中具有最小值 X 的最小索引

📅  最后修改于: 2021-09-06 05:19:13             🧑  作者: Mango

给定一个大小为N的数组arr[]和一个由M 个整数组成的数组Q[] ,每个都代表一个查询,每个查询Q[i]的任务是找到值大于或的数组元素的最小索引等于Q[i] 。如果不存在这样的索引,则打印-1

例子:

方法:该问题可以使用二分搜索和前缀和技术解决。请按照以下步骤解决问题:

  • 初始化一个数组,比如storeArrIdx[] ,形式为{ first, second }以存储数组元素和索引。
  • 按数组元素的升序对数组storeArridx[]进行排序。
  • 按升序对数组 arr[] 进行排序。
  • 初始化一个数组,比如minIdx[] ,这样minIdx[i]存储其值大于或等于arr[i]的数组元素的最小索引。
  • 使用变量i反向遍历数组storeArrIdx[] 。对于每个i索引,更新minIdx[i] = min(minIdx[i + 1], storeArrIdx[i].second)
  • 使用变量i遍历数组Q[] 。对于每个i查询,在arr[] 中找到Q[i]的lower_bound 的索引,并检查获得的索引是否小于N。如果发现为真,则打印minIdx[i]
  • 否则,打印-1

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the smallest index
// of an array element whose value is
// less than or equal to Q[i]
void minimumIndex(vector& arr,
                  vector& Q)
{
 
    // Stores size of array
    int N = arr.size();
 
    // Stores coun of queries
    int M = Q.size();
 
    // Store array elements along
    // with the index
    vector > storeArrIdx;
 
    // Store smallest index of an array
    // element whose value is greater
    // than or equal to i
    vector minIdx(N);
 
    // Traverse the array
    for (int i = 0; i < N; ++i) {
 
        // Insert {arr[i], i} into
        // storeArrIdx[]
        storeArrIdx.push_back({ arr[i], i });
    }
 
    // Sort the array
    sort(arr.begin(), arr.end());
 
    // Sort the storeArrIdx
    sort(storeArrIdx.begin(),
         storeArrIdx.end());
 
    // Stores index of arr[N - 1] in
    // sorted order
    minIdx[N - 1]
        = storeArrIdx[N - 1].second;
 
    // Traverse the array storeArrIdx[]
    for (int i = N - 2; i >= 0; i--) {
 
        // Update minIdx[i]
        minIdx[i] = min(minIdx[i + 1],
                        storeArrIdx[i].second);
    }
 
    // Traverse the array Q[]
    for (int i = 0; i < M; i++) {
 
        // Store the index of
        // lower_bound of Q[i]
        int pos
            = lower_bound(arr.begin(),
                          arr.end(), Q[i])
              - arr.begin();
 
        // If no index found whose value
        // greater than or equal to arr[i]
        if (pos == N) {
            cout << -1 << " ";
            continue;
        }
 
        // Print smallest index whose value
        // greater than or equal to Q[i]
        cout << minIdx[pos] << " ";
    }
}
 
// Driver Code
int main()
{
 
    vector arr = { 1, 9 };
    vector Q = { 7, 10, 0 };
 
    minimumIndex(arr, Q);
    return 0;
}


Java
// Java program for above approach
import java.util.*;
import java.lang.*;
class pair
{
  int element,index;
  pair(int element, int index)
  {
    this.element = element;
    this.index = index;
  }
}
class GFG
{
 
  // Function to find the smallest index
  // of an array element whose value is
  // less than or equal to Q[i]
  static void minimumIndex(int[] arr,
                           int[] Q)
  {
 
    // Stores size of array
    int N = arr.length;
 
    // Stores coun of queries
    int M = Q.length;
 
    // Store array elements along
    // with the index
    ArrayList storeArrIdx = new ArrayList<>();
 
    // Store smallest index of an array
    // element whose value is greater
    // than or equal to i
    int[] minIdx = new int[N];
 
    // Traverse the array
    for (int i = 0; i < N; ++i)
    {
 
      // Insert {arr[i], i} into
      // storeArrIdx[]
      storeArrIdx.add(new pair(arr[i], i));
    }
 
    // Sort the array
    Arrays.sort(arr);
 
    // Sort the storeArrIdx
    Collections.sort(storeArrIdx, (a, b)->a.element-b.element);
 
    // Stores index of arr[N - 1] in
    // sorted order
    minIdx[N - 1]
      = storeArrIdx.get(N - 1).index;
 
    // Traverse the array storeArrIdx[]
    for (int i = N - 2; i >= 0; i--) {
 
      // Update minIdx[i]
      minIdx[i] =Math.min(minIdx[i + 1],
                          storeArrIdx.get(i).index);
    }
 
    // Traverse the array Q[]
    for (int i = 0; i < M; i++) {
 
      // Store the index of
      // lower_bound of Q[i]
      int pos
        = lower_bound(arr, Q[i]);
 
      // If no index found whose value
      // greater than or equal to arr[i]
      if (pos == N) {
        System.out.print("-1"+" ");
        continue;
      }
 
      // Print smallest index whose value
      // greater than or equal to Q[i]
      System.out.print(minIdx[pos]+" ");
    }
  }
  static int lower_bound(int[] arr,int element)
  {
    for(int i = 0; i < arr.length; i++)
      if(element <= arr[i])
        return i;
 
    return arr.length; 
  }
 
  // Driver function
  public static void main (String[] args)
  {
    int[] arr = { 1, 9 };
    int[] Q = { 7, 10, 0 };
 
    minimumIndex(arr, Q);
  }
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approachf
from bisect import bisect_left
 
# Function to find the smallest index
# of an array element whose value is
# less than or equal to Q[i]
def minimumIndex(arr, Q):
 
    # Stores size of array
    N = len(arr)
 
    # Stores coun of queries
    M = len(Q)
 
    # Store array elements along
    # with the index
    storeArrIdx = []
 
    # Store smallest index of an array
    # element whose value is greater
    # than or equal to i
    minIdx = [0]*(N)
 
    # Traverse the array
    for i in range(N):
       
        # Insert {arr[i], i} into
        # storeArrIdx[]
        storeArrIdx.append([arr[i], i])
 
    # Sort the array
    arr = sorted(arr)
 
    # Sort the storeArrIdx
    storeArrIdx = sorted(storeArrIdx)
 
    # Stores index of arr[N - 1] in
    # sorted order
    minIdx[N - 1] = storeArrIdx[N - 1][1]
 
    # Traverse the array storeArrIdx[]
    for i in range(N - 2, -1, -1):
 
        # Update minIdx[i]
        minIdx[i] = min(minIdx[i + 1], storeArrIdx[i][1])
 
    # Traverse the array Q[]
    for i in range(M):
 
        # Store the index of
        # lower_bound of Q[i]
        pos = bisect_left(arr, Q[i])
 
        # If no index found whose value
        # greater than or equal to arr[i]
        if (pos == N):
            print(-1, end = " ")
            continue
 
        # Prsmallest index whose value
        # greater than or equal to Q[i]
        print(minIdx[pos], end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 9]
    Q = [7, 10, 0]
    minimumIndex(arr, Q)
 
    # This code is contributed by mohit kumar 29


输出:
1 -1 0

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live