给出了一个由N个整数组成的零索引数组A.数组的旋转意味着每个元素被右移一个索引,数组的最后一个元素也被移到第一位。
例如,数组A= is的旋转。目标是旋转数组A、K次;也就是说,A的每个元素都将被K索引移到右边。
function solution($A, $K) {
// when array is empty or has only one element
if(count($A) == 0 || count($A) == 1){
return $A;
}
//runs k times
for($j=1; $j<=$K; $j++){
$last_element = $A[count($A)-1];
//runs for each element
for($i=(count($A)-1); $i>0; $i--){
$A[$i] = $A[$i-1];
}
$A[0] = $last_element;
}
return $A;
}
$A = [1, 2, 3, 4];
$K = 4;
$result = solution($A, $K);
print_r($result);Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)发布于 2018-03-17 16:23:18
你可以使用数组函数。它们简化并加速了数组的处理。请参阅:http://php.net/manual/en/ref.array.php
所以你的代码可以变成:
function rotateArray($inputArray,$rightShiftCount)
// shift all elements of the array to the right a number of times
{
// extract the part of the array to move to the front
$partToMove = array_splice($inputArray,-($rightShiftCount % count($inputArray)));
// return extract part followed by what was left of the array
return array_merge($partToMove,$inputArray);
}此函数不检查其参数,如果需要,可以添加该参数。
注意,我为变量使用了合理的名称,而不是$A和$K。这是故意的。
发布于 2022-06-17 13:57:10
solution可能是一个可以接受的函数名,但在实际应用程序中,尝试给您的函数一个直观的名称来描述其功能。代码:(演示)
function popUnshift(array $indexedArray, int $popShiftsCount): array
{
$count = count($indexedArray);
if ($count < 2) {
return $indexedArray;
}
$remainder = $popShiftsCount % $count;
if (!$remainder) {
return $indexedArray;
}
return array_merge(
array_splice($indexedArray, -$remainder),
$indexedArray
);
}发布于 2018-03-17 12:59:29
实际上,您不需要旋转初始数组的K时间:
0; $i--) {
$A[$i] = $A[$i - 1];
}
$A[0] = $last_element;
}
return $A;
}https://codereview.stackexchange.com/questions/189734
复制相似问题