C ++中数组中存在的最大连续数
给定一个正整数数组。目的是找到其中存在的最大连续数。首先,我们将对数组进行排序,然后比较相邻元素arr[j]==arr[i]+1(j=i+1),如果差为1,则递增计数,索引i++,j++,否则更改计数=1。将到目前为止找到的最大计数存储在maxc中。
输入值
Arr[]= { 100,21,24,73,22,23 }输出结果
Maximum consecutive numbers in array : 4
说明-排序后的数组为-{21,22,23,24,73,100}初始化count=1,maxcount=1
1. 22=21+1 count=2 maxcount=2 i++,j++ 2. 23=22+2 count=3 maxcount=3 i++,j++ 3. 24=23+1 count=4 maxcount=4 i++,j++ 4. 73=24+1 X count=1 maxcount=4 i++,j++ 5. 100=73+1 X count=1 maxcount=4 i++,j++
最大连续数为4{21,22,23,24}
输入值
Arr[]= { 11,41,21,42,61,43,9,44 }输出结果
Maximum consecutive numbers in array : 4
说明-排序后的数组为-{9,11,21,41,42,43,44,61}初始化count=1,maxcount=1
1. 11=9+1 X count=1 maxcount=1 i++,j++ 2. 21=11+1 X count=1 maxcount=1 i++,j++ 3. 41=21+1 X count=1 maxcount=1 i++,j++ 4. 42=41+1 count=2 maxcount=2 i++,j++ 5. 43=42+1 count=3 maxcount=3 i++,j++ 6. 44=43+1 count=4 maxcount=4 i++,j++ 7. 61=44+1 X count=1 maxcount=4 i++,j++
最大连续数为4{41,42,43,44}
以下程序中使用的方法如下
整数数组Arr[]用于存储整数。
整数“n”存储数组的长度。
函数subs(intarr[],intn)接受一个数组,其大小作为输入并返回数组中存在的最大连续数。
首先,我们将使用sort(arr,arr+n)对数组进行排序
现在初始化count=1和maxc=1。
从两个for循环中的前两个元素arr[0]和arr[1]开始,比较arr[j]==arr[i]+1(j=i+1),如果为true,则递增计数和i加1。
如果以上条件为假,请再次将count更改为1。用迄今为止找到的最高计数更新maxc(maxc=count>maxc?count:maxc)。
最后,返回maxc作为最大连续元素数。
示例
#include <iostream>
#include <algorithm>
using namespace std;
int subs(int arr[],int n){
std::sort(arr,arr+n);
int count=1;
int maxc=1;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(arr[j]==arr[i]+1){
count++;
i++;
}
else
count=1;
maxc=count>maxc?count:maxc;
}
}
return maxc;
}
int main(){
int arr[] = { 10,9,8,7,3,2,1,4,5,6 };
int n = sizeof(arr) / sizeof(int);
cout << "数组中存在的最大连续数:"<<subs(arr, n);
return 0;
}输出结果
数组中存在的最大连续数: 10