189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 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]
Example 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]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
本题的意思是给定一个数组,将数组向右旋转k步,其中k是非负的
此处可以先来复习一下python的两个方法:insert()和pop()
insert() 函数用于将指定对象插入列表的指定位置。
insert()方法语法:
list.insert(index, obj)
- index -- 对象 obj 需要插入的索引位置。
- obj -- 要插入列表中的对象。
该方法没有返回值,但会在列表指定位置插入对象。
pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
pop()方法语法:
list.pop([index=-1])
- obj -- 可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值。
该方法返回从列表中移除的元素对象。
所以本题可以利用这两个方法来求解
class Solution:
def rotate(self, nums, k):
while k>0:
nums.insert(0,nums.pop())
k-=1
268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1] Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
class Solution:
def missingNumber(self, nums):
n=len(nums)
asum=n*(n+1)//2
return asum-sum(nums)