4 回答

TA貢獻1798條經驗 獲得超3個贊
您可以組合使用array_pop(),這會彈出數組的最后一個元素,并將array_unshift()其推到數組的前面。您可以為此創建一個簡單的函數,
function array_pop_unshift($array) {
array_unshift($array, array_pop($array));
return $array;
}
然后將其用作
$a = [1,2,3,4,5];
$new = array_pop_unshift($a);
print_r($new); // [5,1,2,3,4]
要繼續移動它,只需再次調用該函數直到完成,例如通過循環for,
$a = [1,2,3,4,5];
for ($i = 0; $i < 2; $i++) {
$new = array_pop_unshift($a);
}
print_r($new); // [4,5,1,2,3]

TA貢獻1811條經驗 獲得超6個贊
array_unshift如果您想避免多個and的成本array_pop,您可以構建一個使用數組內部指針的生成器。如果您確實需要結果數組,請使用以下方法iterator_to_array()創建它:
$a = range(1,5);
function rotate(&$array, $step = 1) {
$length = count($array);
end($array);
while ($step--)
prev($array);
while ($length--) {
next($array);
if (key($array) === null)
reset($array);
yield current($array);
}
}
print_r(iterator_to_array(rotate($a, 2))); // [4,5,1,2,3]
請注意,rotate()
生成器使用引用來避免數組復制,但不會修改原始數組:它僅將數組指針從所選位置移動 n 次(其中 n 是數組長度)。當數組指針超出數組時(key()
返回null
),數組指針將被重置。換句話說,即使有一個大數組和多次旋轉(我在代碼中稱之為“步驟”),它仍然保持高效。

TA貢獻1796條經驗 獲得超4個贊
不要迭代調用array_pop()
和array_unshift()
,而是使用一種高效、優雅的方法來減少函數調用并具有盡可能低的時間復雜度。使用提前返回可以防止對相同結果進行不必要的函數調用。
代碼:(演示)
function popUnshift(array $indexedArray, int $popShiftsCount): array
{
$count = count($indexedArray);
if ($count < 2) {
return $indexedArray; // array cannot be rotated
}
$remainder = $popShiftsCount % $count;
if (!$remainder) {
return $indexedArray; // sought rotation is the original order
}
return array_merge(
array_splice($indexedArray, -$remainder),
$indexedArray
);
}
披露:這個答案是建立在 CodeReview 頁面(PHP 中的 Codility 循環輪換解決方案)上的,我在評論中提供了這個片段。

TA貢獻1803條經驗 獲得超6個贊
您實際上是在進行右旋轉,而不是左旋轉。無論如何,這里有執行這兩個操作的函數。它們可能不是最有效的,但它們的代碼很短并且非常不言自明:
<?php
function rotateLeft($array, $times) {
for($i=0; $i<$times; $i++){
$array[] = array_shift($array);
}
return $array;
}
function rotateRight($array, $times) {
for($i=0; $i<$times; $i++){
array_unshift($array, array_pop($array));
}
return $array;
}
$a = [1,2,3,4,5];
$a = rotateRight($a, 1);
print_r($a);
?>
- 4 回答
- 0 關注
- 159 瀏覽
添加回答
舉報