📌  相关文章
📜  检查每个子数组是否由其长度内的所有自然数组成

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

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

例子:

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

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

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

  • 创建一个映射,例如Map ,以存储给定数组的每个元素的位置。
  • 遍历数组并将数组中每个元素的位置存储到Map 上
  • 创建一个集合,比如st来存储范围[1, N]中每个元素的索引。
  • 初始化两个变量,例如MinMax ,以存储st 中存在的最小和最大元素。
  • 迭代范围[1, N]并将Map[i]的值插入st并检查是否Max – Min + 1 = i 。如果发现为真,则打印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


Javascript


输出:
True False False True

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

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