35. Search Insert Position
输入一个排好序的列表和一个目标值,求这个目标值在列表中的索引,不在的话求这个目标值排序时应该在列表中位置的索引
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 1:
Input: [1,3,5,6], 0 Output: 0我的代码:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)):
if nums[i] >= target:
return i
return i+1
大神的代码:一行解决
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return len([x for x in nums if x<target])
53. Maximum Subarray
给出一个列表,求其中连续子列表相加得到的最大数
我的代码:主要思路正确就能解决,一开始没有考虑到全为负数的情况,直接调用max()函数只会增加计算量,在遍历过程中再加了个标志
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:return nums[0]
max_ = nums[0]
sum_ = 0
max_num = nums[0]
for i in nums:
sum_ = max(sum_ + i, 0) #可改进
max_ = max(max_,sum_)
max_num = max(max_num,i)
return max_ if max_num > 0 else max_num
大神的代码:思路大致一致,所设的标志比我更好
def maxSubArray(self, A):
if not A:
return 0
curSum = maxSum = A[0]
for num in A[1:]:
curSum = max(num, curSum + num) #这步是我没想到的
maxSum = max(maxSum, curSum)
return maxSum
728. Self Dividing Numbers
如果一个数能分别被他包含的每个数整除,则符合要求
输入一个范围,求这个范围内所有符合条件的数列表
Example 1:
Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]我的代码:
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
def Isdn(n):
for i in str(n):
if i == '0' or n % int(i) != 0:
return False
return True
ans = []
for i in range(left,right+1):
if Isdn(i):
ans.append(i)
return ans
大神的代码:写一个函数判断,然后用filter函数
class Solution(object):
def selfDividingNumbers(self, left, right):
is_self_dividing = lambda num: '0' not in str(num) and all([num % int(digit) == 0 for digit in str(num)])
return filter(is_self_dividing, range(left, right + 1))
As pointed out by @ManuelP, [num % int(digit) == 0 for digit in str(num)]
creates an entire list which is not necessary. By leaving out the [
and ]
, we can make use of generators which are lazy and allows for short-circuit evaluation, i.e. all
will terminate as soon as one of the digits fail the check.
意思是其实all函数输入一个迭代器就可以了,用[]会计算所有数,而不用[]会产生一个生成器,惰性去计算,一旦不符合要求就会退出
The answer below improves the run time from 128 ms to 95 ms:
class Solution(object):
def selfDividingNumbers(self, left, right):
is_self_dividing = lambda num: '0' not in str(num) and all(num % int(digit) == 0 for digit in str(num))
return filter(is_self_dividing, range(left, right + 1))