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( int arr[], int n) 以数组及其大小作为输入,并返回数组中存在的最大连续数字。
首先,我们将使用 sort(arr,arr+n) 对数组进行排序。
现在初始化 count=1 和 maxc=1。
从前两个元素 arr[0] 和 arr[1] 开始,在两个 for 循环内,比较 arr[j]==arr[i]+1(j=i+1)是否成立,如果成立,则将 i 递增 1 并递增计数。
如果上述条件为假,则再次将计数更改为 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 << "Maximum consecutive numbers present in an array :"<<subs(arr, n);
return 0;
}输出
Maximum consecutive numbers present in an array : 10
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP