簡體   English   中英

PHP的array_slice與Python的拆分數組

[英]PHP's array_slice vs Python's splitting arrays

一些背景

我正在嘗試常見的“ MaxProfit”編程挑戰。 它基本上是這樣的:

給定零索引數組A(包含N個整數),其中N個整數包含連續N天的股票價格,則返回該期間一次交易的最大可能利潤。

避免了幼稚的蠻力嘗試,我對我提出的PHP算法感到非常滿意:

public function maxProfit($prices)
{
    $maxProfit = 0;
    $key = 0;
    $n = count($prices);

    while ($key < $n - 1) {
        $buyPrice = $prices[$key];
        $maxFuturePrice = max( array_slice($prices, $key+1) );          
        $profit = $maxFuturePrice - $buyPrice;

        if ($profit > $maxProfit) $maxProfit = $profit;
        $key++;
    }
    return $maxProfit;
}

但是,測試了我的解決方案后,它似乎在性能方面表現不佳,甚至在O(n 2 )時間內也是如此。

我做了一些閱讀,發現了一個非常相似的python解決方案。 Python具有一些非常方便的數組功能,可以使用a a[s : e]語法拆分數組,這與PHP中我使用array_slice函數的方式不同。 我認為這一定是瓶頸,所以我做了一些測試:

測驗

PHP array_slice()

$n = 10000;    
$a = range(0,$n);

$start = microtime(1);
foreach ($a as $key => $elem) {
    $subArray = array_slice($a, $key);
}
$end = microtime(1);

echo sprintf("Time taken: %sms", round(1000 * ($end - $start), 4)) . PHP_EOL;

結果:

$ php phpSlice.php
Time taken: 4473.9199ms
Time taken: 4474.633ms
Time taken: 4499.434ms

Python a [s:e]

import time

n = 10000
a = range(0, n)

start = time.time()
for key, elem in enumerate(a):
    subArray = a[key : ]
end = time.time()

print "Time taken: {0}ms".format(round(1000 * (end - start), 4))

結果:

$ python pySlice.py 
Time taken: 213.202ms
Time taken: 212.198ms
Time taken: 215.7381ms
Time taken: 213.8121ms

  1. 為什么PHP的array_slice()效率比Python低20倍?
  2. PHP中是否有一種等效的有效方法可以實現上述目標,從而有望使我的maxProfit算法在O(N)時間內運行? 編輯我意識到我上面的實現實際上不是O(N),但是我的問題仍然在於切片數組的效率。
  1. 我真的不知道,但是PHP的數組搞砸了混合怪物,這也許就是原因。 Python的列表實際上只是列表,而不是同時包含字典,因此,它們可能更簡單/更快。
  2. 是的,做一個實際的O(n)解。 您的解決方案不僅因為PHP的切片速度很慢而很慢,而且因為您顯然具有O(n ^ 2)算法而很慢。 只需遍歷陣列一次,跟蹤到目前為止找到的最低價格,並用當前價格進行檢查。 每次循環迭代時, max都不超過數組的一半。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM