两算法:求数组元素出现次数和求子数组最大和

来源:互联网 发布:淘宝怎么查自己的排名 编辑:程序博客网 时间:2024/05/28 05:16

一. 求数组元素出现次数

给出一含有十个数的数组,构建一新数组,要求新数组中的每个数是先前数组中相对应元素在新数组中出现的次数。   
给出数组为:   
[0,1,2,3,4,5,6,7,8,9]

举一个例子,   
数值: 0,1,2,3,4,5,6,7,8,9   
分配: 6,2,1,0,0,0,1,0,0,0   
0在出现了6次,1在出现了2次,   
2在出现了1次,3在出现了0次....   
以此类推.. 

思路:采用假设检验法

class BottomNum{    private $top = array();    //给出的数组    private $bottom = array(); //要求构建的新数组       private $success = false;  //检验是否成功    function __CONSTRUCT()    {        for($i=0;$i<10;$i++)        {            $this->top[$i] = $i;            $this->bottom[$i] = 0;        }    }    function getBottom()    {        while(!$this->success)        {            $this->success = $this->setBottom();        }        var_dump($this->bottom);    }    function setBottom()    {        $result = true;        for($i=0;$i<10;$i++)        {            $fre = $this->getFrequecy($i);            if($fre != $this->bottom[$i])    //检验失败             {                $this->bottom[$i] = $fre;                $result=false;            }        }        return $result;    }    function getFrequecy($num)    {        $count=0;        for($i=0;$i<10;$i++)        {            if($this->bottom[$i]==$num)                ++$count;        }        return $count;    }}$bottomNum = new BottomNum();$bottomNum->getBottom();

二. 求子数组最大和
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。

function subMaxSum($array){    $sum=0;    $tmp=0;    foreach($array as $v)    {        $tmp=$tmp+$v;        if($tmp>$sum){            $sum=$tmp;        }        elseif($tmp<=0)        {            $tmp=0;        }    }    echo $sum;}