Rotate Array Leetcode python

https://leetcode.com/problems/rotate-array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question

Solution 1:

Runtime: 80 ms
Space O(n) 
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k = k%l
numscopy = list(nums)
numscopy = numscopy[l-k:] + numscopy[:l-k]
for i,num in enumerate(numscopy):
nums[i] = num

Solution 2:
[1,2,3,4] is the first part
[5,6,7] is the second part

Reverse the first part first, then reverse the second part, then revert the whole string
[4, 3, 2, 1, 5, 6, 7]
[4, 3, 2, 1, 7, 6, 5]
[5, 6, 7, 1, 2, 3, 4]
Runtime: 100 ms

class Solution(object):
def rotate(self, nums, k):
l = len(nums)
k = k%l
self.nums = nums
self.reverse2(0,l-k)
self.reverse2(l-k,l)
self.reverse2(0,l)
# reverse the subarray
def reverse(self,start,end):
self.nums[start:end] = self.nums[start:end][::-1]
def reverse2(self,start,end):
end -=1
while start < end:
self.nums[start],self.nums[end] = self.nums[end],self.nums[start]
start+=1
end-=1


Similiar Questions:
https://leetcode.com/problems/rotate-list/ 
If it's link list then, we don't need to make a copy of array 
Just connect tail and head, 
Use two pointers to find the tail and k-1 node before tail, 
To find these two nodes, one node start from beginning the other one starts from k step from beginning, when the leading one reaches the end it's k node ahead of the other one


Runtime: 68 ms
class Solution:
# @param {ListNode} head
# @param {integer} k
# @return {ListNode}
def rotateRight(self, head, k):
if k <= 0:
return head
current = head
count = 0 
while(current != None):
count+=1
current = current.next
if count == 0:
return None
k = k%count
current = head
for i in xrange(k):
current = current.next
p2 = head
while (current.next != None):
current = current.next
p2 = p2.next
current.next = head
newhead = p2.next
p2.next = None

return newhead


评论

此博客中的热门博文

Embedded System interview Question

MicroKernel & Exokernel 操作系统未来可能的发展

中国城市房地产分析