我在leetcode中读到了这样的问题
给出一个数组,将数组向右旋转 k 步,其中 k 为非负数。
示例1:
Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
示例2:
Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
注意:
- 尝试提供尽可能多的解决方案,至少有3种不同的方法来解决此问题。
- 您可以在原位使用O(1)多余的空间吗?
它的官方解决方案是用Java编写的
public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int count = 0;
for (int start = 0; count < nums.length; start++) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % nums.length;
int temp = nums[next];
nums[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
}
我试图将其翻译为python
class Solution3:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
count = 0
start = 0
while count < len(nums):
current = start
prev = nums[start] #store the value in the position
while start != current:
next = (current + k) % len(nums)
temp = nums[next]
nums[next] = prev
prev = temp #store the value
current = next
count += 1
但是,没有do while
如何处理这种情况?
答案 0 :(得分:1)
在Python中,您可以像这样模拟do while
的行为
while True:
do_things()
if not cond:
break
所以在您的情况下:
while True:
next = (current + k) % len(nums)
temp = nums[next]
nums[next] = prev
prev = temp #store the value
current = next
count += 1
if start == current:
break