python 动态求和
输入:nums = [1,2,3,4] 输出:[1,3,6,10]
class Solution(object):
def runningSum(self, nums):
ls=[]
a=0
for i in range(len(nums)):
a=a+nums[i]
ls.append(a)
return ls
python 给你一串数组,要找出最大和的子字符串,并返回
# You should return your result.
import numpy as np
def maxSubArray(nums):
if len(nums)==1:
return nums[0]
# 用来存放每次更新的最大子串和
if len(nums) > 1:
max_ret = nums[0]
cur_max = last_max = nums[0]
# 状态转移方程,一步步的分解子问题
for i in range(1,len(nums)):
if last_max+nums[i] < nums[i]:
cur_max = nums[i]
else:
cur_max = last_max+nums[i]
if cur_max > max_ret:
max_ret = cur_max
last_max = cur_max
return max_ret
maxSubArray(np.array([-2,1,-3,4,-1,2,1,-5,4]))
python 给你一串数组,要找出最大乘积的子字符串,并返回
def maxProduct(nums):
if len(nums)==1:
return nums[0]
# max_ret用来存放每次更新的最大子串乘积
if len(nums) > 1:
max_ret = nums[0]
cur_max = last_max = nums[0]
# 状态转移方程,一步步的分解子问题
for i in range(1,len(nums)):
if cur_max*nums[i] < nums[i]:
cur_max = nums[i]
else:
cur_max = cur_max*nums[i]
if cur_max > max_ret:
max_ret = cur_max
# last_max = cur_max
return max_ret
ransmoNote 的字符是否都可以再magazine 中找到
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
return all(magazine.count(i)>=ransomNote.count(i) for i in set(ransomNote))
python 判断数组内是否有重复的元素
例子: 输入:nums = [1,2,3,1] 输出:true
先不数组排序,这样重复元素就会挨一起,用一个值来循环遍历,当循环到与下一个元素一样的就返回True
def containsDuplicate(, nums):
nums.sort()
count = 0
while count<len(nums)-1:
if nums[count]==nums[count+1]:
return True
count += 1
return False