检查数组元素是否连续
时间:2020-02-23 14:33:58 来源:igfitidea点击:
在本教程中,我们将看到如何检查数组元素是否连续。
问题
给定数组,我们需要检查数组是否包含连续元素。
例如:
Input: array[] = {5, 3, 4, 1, 2}
Output: true
As array contains consecutive elements from 1 to 5
Input: array[] = {47, 43, 45, 44, 46}
Output: true
As array contains consecutive elements from 43 to 47
Input: array[] = {6, 7, 5, 6}
Output: false
As array does not contain consecutive elements.
解决方案
简单的解决方案是对数组进行排序并检查元素是否通过迭代过度迭代,但该解决方案的时间复杂度将是O(n ^ logn)。
我们可以做得更好吗?
是的,我们可以做得更好
- 在数组中查找最小和最大元素。
- 检查MAX-MIN + 1 == N,如果元素是连续的,则此条件应满足。
- 创建访问过的布尔数组。
- 迭代阵列并检查
- 访问过[arr [i] -min]是真的,然后返回false,因为重复元素。
- 标记已访问的元素。
要检查数组元素是否连续的程序
package org.arpit.theitroad;
public class ArrayConsecutiveElementMain{
/* Method return minimum value*/
private int getMinimum(int arr[], int n)
{
int min = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
/* Method return maximum value*/
private int getMaximum(int arr[], int n)
{
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
/* This method checks if array elements are consecutive */
public boolean checkArrayContainsConsecutiveElements(int arr[], int n)
{
if ( n < 1 )
return false;
int min = getMinimum(arr, n);
int max = getMaximum(arr, n);
if (max - min + 1 == n)
{
boolean[] visited=new boolean[arr.length];
for (int i = 0; i < n; i++)
{
if ( visited[arr[i] - min] != false )
return false;
visited[arr[i] - min] = true;
}
return true;
}
return false;
}
public static void main(String args[])
{
ArrayConsecutiveElementMain acem=new ArrayConsecutiveElementMain();
int arr[]= {47, 43, 45, 44, 46};
if(acem.checkArrayContainsConsecutiveElements(arr, arr.length))
System.out.println(" Array elements are consecutive ");
else
System.out.println(" Array elements are not consecutive ");
return;
}
}
运行上面的程序时,我们将得到以下输出:
Array elements are consecutive
该解决方案的时间复杂性是O(n)。

