[英]Right rotation of an array by slicing
I am trying to do an in-place right rotation of an array nums
k
times.我正在尝试对数组
nums
k
次进行就地右旋转。 I can't get my head around why my code works for one array and fails for another.我无法理解为什么我的代码对一个数组有效而对另一个数组无效。
Code - nums[:]=nums[-k:]+nums[:k+1]
代码 -
nums[:]=nums[-k:]+nums[:k+1]
Works for nums=[1,2,3,4,5,6,7]
and k=3
适用于
nums=[1,2,3,4,5,6,7]
和k=3
Output - nums=[5, 6, 7, 1, 2, 3, 4]
Output -
nums=[5, 6, 7, 1, 2, 3, 4]
Fails for nums=[-1,-100,3,99]
k=2
失败
nums=[-1,-100,3,99]
k=2
Output - [3, 99, -1, -100, 3]
Desired Output - [3, 99, -1, -100]
Output -
[3, 99, -1, -100, 3]
所需 Output - [3, 99, -1, -100]
I found a solution in https://www.geeksforgeeks.org/python-ways-to-rotate-a-list/我在https://www.geeksforgeeks.org/python-ways-to-rotate-a-list/中找到了解决方案
It says you can rotate right by doing它说你可以通过做
nums=[-1,-100,3,99]
k = 2
nums = nums[-k:] + nums[:-k]
print(nums)
The output is [3, 99, -1, -100]
output 为
[3, 99, -1, -100]
Explanation: First, you take the desired ( k
) number of elements from the right side of the list and place them as the start of the rotated list ( nums[-k:]
).说明:首先,您从列表右侧获取所需的 (
k
) 个元素并将它们作为旋转列表的开始 ( nums[-k:]
)。 Second, you take the left side of the list and place it at the end of the new list ( nums[:-k]
).其次,您将列表的左侧放在新列表的末尾(
nums[:-k]
)。 This will not work if k > len(nums)
.如果
k > len(nums)
这将不起作用。
both outputs are logical.两个输出都是合乎逻辑的。
#nums[-k:] is [3,99]
#nums[:k+1] is [-1,-100,3]
#Output is [3, 99, -1, -100,3]
i think your solution isn't optimal i think this might help you: [1]: https://www.techiedelight.com/right-rotate-an-array-k-times/我认为您的解决方案不是最佳的,我认为这可能会对您有所帮助:[1]: https://www.techiedelight.com/right-rotate-an-array-k-times/
PHP solution: PHP 解决方案:
slice array into 2 parts and merge in reverse order.将数组切成两部分并以相反的顺序合并。
$c = count($A);
$a1 = array_splice($A,0,$c - $K );
$a2 = $A;
return array_merge($a2,$a1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.