📌  相关文章
📜  检查每个子数组是否包含所有不超过其长度的自然数

📅  最后修改于: 2021-05-17 22:46:04             🧑  作者: Mango

给定一个数组arr []表示范围为[1,N]的前N个自然数的排列,每个i索引的任务是检查是否存在一个i长度子数组,以使其包含所有[1,i]范围内的数字。
注意: 1 –使用基于索引的索引。

例子:

天真的方法:想法是遍历数组,对于每个索引,检查是否存在大小为i的子数组,该子数组包含[1,i]范围内的所有数字。如果发现为true,则打印True 。否则,打印False。

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

高效的方法:可以使用散列来有效地存储给定数组的每个元素的位置来解决该问题。请按照以下步骤解决问题:

  • 创建一个地图,例如Map ,以存储给定数组中每个元素的位置。
  • 遍历数组并将数组中每个元素的位置存储到Map中
  • 创建一个集合,比如说st,以存储范围[1,N]中每个元素的索引。
  • 初始化两个变量,例如MinMax ,以存储st中存在的最小和最大元素。
  • 迭代[1,N]范围然后将Map [i]的值插入st并检查Max – Min + 1 = i 。如果发现为true,则打印True
  • 否则,输出False

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to check if a subarray of size i exists
// that contain all the numbers in the range [1, i]
void checksubarrayExist1_N(int arr[], int N)
{
 
    // Store the position
    // of each element of arr[]
    unordered_map pos;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert the position
        // of arr[i]
        pos[arr[i]] = i;
    }
 
    // Store position of each element
    // from the range [1, N]
    set st;
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
        // Insert the index of i into st
        st.insert(pos[i]);
        // Find the smallest element of st
        int Min = *(st.begin());
 
        // Find the largest element of st
        int Max = *(st.rbegin());
 
        // If distance between the largest
        // and smallest element of arr[]
        // till i-th index is equal to i
        if (Max - Min + 1 == i) {
            cout << "True ";
        }
        else {
            cout << "False ";
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 4, 3, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    checksubarrayExist1_N(arr, N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG {
 
  // Function to check if a subarray of size i exists
  // that contain all the numbers in the range [1, i]
  static void checksubarrayExist1_N(int arr[], int N)
  {
 
    // Store the position
    // of each element of arr[]
    Map pos=new HashMap<>();
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
      // Insert the position
      // of arr[i]
      pos.put(arr[i],i);
    }
 
    // Store position of each element
    // from the range [1, N]
    Set st=new HashSet<>();
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
      // Insert the index of i into st
      st.add(pos.get(i));
      // Find the smallest element of st
      int Min = Collections.min(st);
 
      // Find the largest element of st
      int Max = Collections.max(st);
 
      // If distance between the largest
      // and smallest element of arr[]
      // till i-th index is equal to i
      if (Max - Min + 1 == i) {
        System.out.print("True ");
      }
      else {
        System.out.print("False ");
      }
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 1, 4, 3, 2 };
    int N = arr.length;
 
    checksubarrayExist1_N(arr, N);
  }
}
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
 
# Function to check if a subarray of size i exists
# that contain all the numbers in the range [1, i]
def checksubarrayExist1_N(arr, N):
 
    # Store the position
    # of each element of arr[]
    pos = {}
 
    # Traverse the array
    for i in range(N):
       
        # Insert the position
        # of arr[i]
        pos[arr[i]] = i
 
    # Store position of each element
    # from the range [1, N]
    st = {}
 
    # Iterate over the range [1, N]
    for i in range(1, N + 1):
 
        # Insert the index of i into st
        st[pos[i]] = 1
 
        # Find the smallest element of st
        Min = sorted(list(st.keys()))[0]
 
        # Find the largest element of st
        Max = sorted(list(st.keys()))[-1]
 
        # If distance between the largest
        # and smallest element of arr[]
        # till i-th index is equal to i
        if (Max - Min + 1 == i):
            print("True", end = " ")
        else:
            print("False", end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 4, 3, 2]
    N = len(arr)
    checksubarrayExist1_N(arr, N)
 
    # This code is contributed by mohit kumar 29.


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
 
// Function to check if a subarray of size i exists
// that contain all the numbers in the range [1, i]
static void checksubarrayExist1_N(int[] arr, int N)
{
     
    // Store the position
    // of each element of arr[]
    Dictionary pos = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Insert the position
        // of arr[i]
        pos[arr[i]] = i;
    }
 
    // Store position of each element
    // from the range [1, N]
    HashSet st = new HashSet();
 
    // Iterate over the range [1, N]
    for(int i = 1; i <= N; i++)
    {
         
        // Insert the index of i into st
        st.Add(pos[i]);
        // Find the smallest element of st
        int Min = st.Min();
 
        // Find the largest element of st
        int Max = st.Max();
 
        // If distance between the largest
        // and smallest element of arr[]
        // till i-th index is equal to i
        if (Max - Min + 1 == i)
        {
            Console.Write("True ");
        }
        else
        {
            Console.Write("False ");
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int[] arr = { 1, 4, 3, 2 };
    int N = arr.Length;
 
    checksubarrayExist1_N(arr, N);
}
}
 
// This code is contributed by ukasp


输出:
True False False True

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