Move Zeroes (#283)
来源:https://leetcode.com/problems/move-zeroes/description/
题意:
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:[0,1,0,3,12]
输出:[1,3,12,0,0]
分析:
访问一遍数组,记录0的个数tot,并在数组末尾append上tot个0,最后remove去tot个0。利用list的remove函数功能,每次删去的都是数组中的第一个0,不会把末尾的0删去。
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
tot = 0
for i in range(0, n):
if nums[i] == 0:
nums.append(0)
tot = tot+1
for i in range(0, tot):
nums.remove(0)
状态:
这种方式看起来比较慢,排在leetcode榜的很后面。
Search Insert Position (#35)
来源:https://leetcode.com/problems/search-insert-position/description/
题意:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
分析:简单的二分查找。
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l = 0
r = len(nums)-1
while l <= r:
mid = int((l+r)/2)
if nums[mid] < target:
l = mid+1
else:
r = mid-1
return l
状态: