📅  最后修改于: 2023-12-03 14:58:22.626000             🧑  作者: Mango
This question is from the GATE CS Mock test conducted in 2018. It primarily focuses on data structures and algorithm concepts.
Given an array of integers, the task is to find the maximum length of any subarray of consecutive integers.
Input:
[2, 0, 2, 1, 4, 3, 1, 0]
Output:
Length of the longest consecutive subarray is 5
We can solve this problem using the following approach:
hashSet
.function findMaxLength(arr):
n = length of arr
hashSet = empty set
maxLength = 0
length = 0
for i from 0 to n-1:
if arr[i] not in hashSet:
hashSet.add(arr[i])
length = 1
j = arr[i] + 1
while j in hashSet:
hashSet.add(j)
length = length + 1
j = j + 1
j = arr[i] - 1
while j in hashSet:
hashSet.add(j)
length = length + 1
j = j - 1
maxLength = max(maxLength, length)
return maxLength
The problem of finding the maximum length of a subarray of consecutive integers is an interesting problem that can be solved efficiently using hash sets. It's a good exercise to practice data structure and algorithm concepts.