国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

php數據流中第K大元素的計算方法及代碼分析

瀏覽:3日期:2022-09-06 17:01:36

設計一個找到數據流中第K大元素的類(class)。注意是排序后的第K大元素,不是第K個不同的元素。

計算方法

1、直接使用最小堆,堆的大小為 k,這樣保證空間占用最小,最小堆的根節點是就是最小值,也是我們想要的結果。

2、php的spl標準庫是有最小堆這個庫,直接在代碼中繼承SplMinHeap。

實例

class KthLargest extends SplMinHeap { /** * @param Integer $k * @param Integer[] $nums */ static $nums; public $k; function __construct($k, $nums) {$this->k = $k;// 遍歷初始化數組,分別插入堆中foreach ($nums as $v) { $this->add($v);} } * @param Integer $val * @return Integer function add($val) { // 維持堆的大小為k,當堆還未滿時,插入數據。if ($this->count() < $this->k) { $this->insert($val);} elseif ($this->top() < $val) {// 當堆滿的時候,比較要插入元素和堆頂元素大小。大于堆頂的插入。堆頂移除。 $this->extract();return $this->top(); }} * Your KthLargest object will be instantiated and called as such: * $obj = KthLargest($k, $nums); * $ret_1 = $obj->add($val);

實例擴展:

class KthLargest { /** * @param Integer $k * @param Integer[] $nums */ static $nums; public $k; function __construct($k, $nums) {$this->k = $k;$this->nums = $nums; } /** * @param Integer $val * @return Integer */ function add($val) {array_push($this->nums, $val);rsort($this->nums);return $this->nums[$this->k - 1]; }}

第一個思路,時間超限的原因是每次都要對$this->nums這個數組,進行重新排序,上次已經排序好的,還要再重新排一次,浪費時間。所以,下面的解法是,每次只保存,上次排序完的前k個元素。這次的進行排序的次數就減少了。時間也減少了。

class KthLargest { /** * @param Integer $k * @param Integer[] $nums */ static $nums; public $k; function __construct($k, $nums) {$this->k = $k;$this->nums = $nums; } /** * @param Integer $val * @return Integer */ function add($val) {array_push($this->nums, $val);rsort($this->nums);$this->nums = array_slice($this->nums, 0, $this->k);return $this->nums[$this->k - 1]; }}

到此這篇關于php數據流中第K大元素的計算方法及代碼分析的文章就介紹到這了,更多相關php數據流中第K大元素的計算方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: PHP
相關文章:
主站蜘蛛池模板: 安泽县| 临洮县| 望都县| 黑河市| 武穴市| 明星| 阿荣旗| 当涂县| 疏勒县| 镇坪县| 启东市| 宜都市| 临猗县| 玛多县| 赤壁市| 黎平县| 东辽县| 叶城县| 梁平县| 志丹县| 宕昌县| 固镇县| 德清县| 福贡县| 荥经县| 余江县| 娱乐| 英吉沙县| 北碚区| 依兰县| 汝州市| 榆林市| 恩施市| 舟山市| 汝州市| 馆陶县| 陕西省| 涡阳县| 庐江县| 唐海县| 泸溪县|