所以这里的答案适用于C,但我试图用PHP,以特定的方式做到这一点。
我有一系列这样的数字:
7,2,6,3,10
我想找到按给定顺序首先发生的增长最长的子序列。因此,例如在这种情况下,我希望结果为:
2,6,10
而不是2,3,10。
实现这一目标的最佳方法是什么?
答案 0 :(得分:0)
好的,这是你的问题的解决方案,产生你期望的答案。基本上,对于找到的每个元素,当它们大于列表中的最后一个项目时,它会启动一个列表并添加项目。
$input = array(7,2,6,3,10);
$trial = array();
echo "Input: ";
print_r($input);
echo "<br><br>\n";
foreach ($input as $key => $value)
{
// Create a new trial for each starting point
// ------------------------------------------
$trial[$key][0] = $value;
echo "Trial $key started<br>\n";
// Process all prior trials
// ------------------------
for ($i = $key-1; $i >= 0; $i--)
{
echo "Looking at trial $i ";
$last = count($trial[$i]) - 1;
$lastval = $trial[$i][$last];
if ( $value > $lastval )
{
$trial[$i][] = $value;
echo "** added $value";
}
echo "<br>\n";
}
echo "<br>\n";
}
// Find first longest trial
// ------------------------
$longest = 0;
foreach ($trial as $key => $list)
{
if ( count($list) > count($trial[$longest]) )
$longest = $key;
}
echo "All trials:<br>\n";
print_r($trial);
echo "<br><br>\n";
echo "First longest sequence:<br>\n";
print_r($trial[$longest]);
如果您拥有非常大的数据集,当然可以采用不同的方式。也就是说,这里有一些“调试”输出显示它的实际效果:
Input: Array ( [0] => 7 [1] => 2 [2] => 6 [3] => 3 [4] => 10 ) Trial 0 started Trial 1 started ... looking at trial 0 Trial 2 started ... looking at trial 1 ** added 6 ... looking at trial 0 Trial 3 started ... looking at trial 2 ... looking at trial 1 ... looking at trial 0 Trial 4 started ... looking at trial 3 ** added 10 ... looking at trial 2 ** added 10 ... looking at trial 1 ** added 10 ... looking at trial 0 ** added 10 All trials: Array ( [0] => Array ( [0] => 7 [1] => 10 ) [1] => Array ( [0] => 2 [1] => 6 [2] => 10 ) [2] => Array ( [0] => 6 [1] => 10 ) [3] => Array ( [0] => 3 [1] => 10 ) [4] => Array ( [0] => 10 ) ) First longest sequence: Array ( [0] => 2 [1] => 6 [2] => 10 )
答案 1 :(得分:0)
试试此代码
<?php
$data = array(7, 2, 6, 3, 10);
$slice_array=array_slice($data,array_search(min($data),$data));
$result=array();
for($i=array_search(min($slice_array),$slice_array);$i<=array_search(max($slice_array),$slice_array);$i++){
if(end($result)<$slice_array[$i]){
array_push($result,$slice_array[$i]);
}
}
print_r($result);
?>
输出
Array ( [0] => 2 [1] => 6 [2] => 10 )