PHP:在数组的连续元素数 [英] PHP: Number of consecutive elements in array
本文介绍了PHP:在数组的连续元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直对一个问题:
查找连续编号的最大群体在数组中。
假设我们有一个数组 [5,43,4,56,3,2,44,57,58,1]
,连续的数字中最大的组这个阵列是5(1,2,3,4,和5)。
该解决方案的算法必须经过时间为O(n)的复杂性。
我已经解决了这个具有以下红宝石code,但我无法将它移植到PHP作为解决方案要求。
的改编= [8,13,14,10,6,7,8,14,5,3,5,2,6,7,4]
结果= []
阶段= []
因为我在编曲:
如果len(阶段)GT; 0,I =阶段[-1] +1!
如果len(阶段)GT; 1:
result.append(阶段)
阶段= []
stage.append㈠
打印结果
解决方案
$ A = [8,13,14,10,6,7,8,14,5,3, 5,2,6,7,4〕;
$水库= [];
$阶段= [];
的foreach($ A $为I){
如果(计数($期)> 0安培;&安培;!$ I = $阶段[计数($期)-1] +1){
如果(计数($阶段)→1){
$水库[] = $阶段;
}
$阶段= [];
}
$级[] = $ I;
}
的print_r($水库);
I have been working on one problem:
Find the largest group of consecutive numbers in an array.
Say we have an array [5, 43, 4, 56, 3, 2, 44, 57, 58, 1]
, the biggest group of consecutive numbers in this array is 5 (1, 2, 3, 4, and 5).
The solution algorithm must be time complexity of O(n).
I have solved this with the following ruby code but I am having trouble porting it to PHP as the solution requires.
arr = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4]
result = []
stage = []
for i in arr:
if len(stage) > 0 and i != stage[-1]+1:
if len(stage) > 1:
result.append(stage)
stage = []
stage.append(i)
print result
解决方案
$a = [8, 13, 14, 10, 6, 7, 8, 14, 5, 3, 5, 2, 6, 7, 4];
$res = [];
$stage = [];
foreach($a as $i) {
if(count($stage) > 0 && $i != $stage[count($stage)-1]+1) {
if(count($stage) > 1) {
$res[] = $stage;
}
$stage = [];
}
$stage[] = $i;
}
print_r($res);
这篇关于PHP:在数组的连续元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文