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
廣告