455.分发饼干
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
# get length of s and g
m = len(g)
n = len(s)
# set pointer for s and g
i=0
j=0
#set up return result
result=0
# sort g and s for looping
g.sort()
s.sort()
# lopp if i is samller than length of g and j si smaller than length of s
while i < m and j < n:
# serve the the children who has samller appetite first
if g[i] <= s[j]:
result += 1
i+=1
j+=1
#if the current cookie does not satify current child, see if a bigger cookie does
else:
j+=1
return result
376. 摆动序列
解题思路:
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#set up result, pre value,cur value
#res is one because it is equal or more than one item and we are
#calculating difference
pre=0
cur=0
res=1
#skip index 1 since we want difference
for i in range(1,len(nums)):
#calculate current difference
cur=nums[i]-nums[i-1]
#if pre*cur equal or smaller than 0
#means it is it satisfy wiggle we can append into res
#and replace pre as cur.
#else we keep calculate new difference
if pre*cur<=0 and cur!=0:
res+=1
pre=cur
return res
53. 最大子序和
暴力:
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res=-float("inf")
#first layer for set up start point, second layer for finding max
for i in range(len(nums)):
sum_=0
for j in range(i,len(nums)):
sum_+=nums[j]
res=max(res,sum_)
return res
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res=-float("inf")
sum_=0
#loop for nums
for i in range(len(nums)):
#get sum
sum_+=nums[i]
#if current sum bigger than res, assign it to res
if sum_>res:
res=sum_
#if sum_<= 0, we can restart from 0
if sum_<= 0:
sum_=0
return res