#mine,循环相加
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
#discussion,字典存差
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], I]
else:
buff_dict[target - nums[i]] = I
26.Remove Duplicates from Sorted Array
#要求在nums上修改,返回截取的长度,以tail为标记推进
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
tail=0
for i in range(len(nums)):
if nums[tail]==nums[I]:
continue
else:
tail+=1
nums[tail]=nums[I]
return tail+1
#remove()移除第一个匹配到的元素
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
try:
while True:
nums.remove(val)
except:
return len(nums)
35. Search Insert Position
#其实就是算有多少个比他小的
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return len([x for x in nums if x
#从第一个开始算,如果为负数或和为负数就记下当前max然后重记
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mMax=nums[0]
mSum=0
for val in nums:
mSum+=val
mMax=max(mMax,mSum)
mSum=max(mSum,0)
return mMax
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
return list(map(int,list(str(int(''.join(map(str,digits)))+1))))
#for a very long data
# digits[-1]+=1
# tail=-1
# while digits[tail]==10:
# digits[tail]=0
# if tail==-len(digits):
# digits.insert(0,1)
# break
# tail-=1
# digits[tail]+=1
# return digits
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
nums1[m:]=nums2
nums1.sort()
def generate(self, numRows):
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1
119. Pascal's Triangle II
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res=[[1]]
for i in range(rowIndex):
res+=[[x+y for x,y in zip(res[-1]+[0],[0]+res[-1])]]
return res[-1]
121. Best Time to Buy and Sell Stock
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit=0
min_price=float('inf')
for price in prices:
min_price=min(price,min_price)
profit=price-min_price
max_profit=max(profit,max_profit)
return max_profit
122. Best Time to Buy and Sell Stock II
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)<2:
return 0
profits=map(lambda x,y:x-y,prices[1:],prices[:-1])
return sum([x if x>0 else 0 for x in profits])
167. Two Sum II - Input array is sorted
#用字典存差值
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
dictMinus={}
for i in range(len(numbers)):
if numbers[i] in dictMinus:
return [dictMinus[numbers[i]]+1,i+1]
dictMinus[target-numbers[i]]=i
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dictCount={}
for num in nums:
if num in dictCount:
dictCount[num]+=1
else:
dictCount[num]=1
if dictCount[num]>len(nums)//2:
return num
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
nums[:]=nums[-k:]+nums[:-k]
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums)!=len(set(nums))
219. Contains Duplicate II
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dictSame={}
for i in range(len(nums)):
if (nums[i] in dictSame) and i-dictSame[nums[i]]<=k:
return True
else:
dictSame[nums[i]]=I
return False
class Solution:
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return len(nums)*(len(nums)+1)//2-sum(nums)
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
c=0
while True:
try:
nums.remove(0)
c+=1
except:
nums+=[0]*c
break
414. Third Maximum Number
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
v=[float('-inf')]*3
for n in nums:
if n not in v:
if n>v[0]:v[:]=[n,v[0],v[1]]
elif n>v[1]:v[:]=[v[0],n,v[1]]
elif n>v[2]:v[:]=[v[0],v[1],n]
return v[0] if float('-inf') in v else v[-1]
448. Find All Numbers Disappeared in an Array
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for num in nums:
index = abs(num) - 1
nums[index] = -abs(nums[index])
return [i + 1 for i, num in enumerate(nums) if num > 0]
485. Max Consecutive Ones
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return max(map(len,''.join(map(str,nums)).split('0')))
532. K-diff Pairs in an Array
class Solution:
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
c = collections.Counter(nums)
if k<0:
return 0
elif k==0:
return sum(v>1 for v in c.values())
elif k>0:
return sum(v+k in c for v in c)
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
flat=sum(nums,[])
if c*r!=len(flat):
return nums
return [flat[x*c:x*c+c] for x in range(r)]
581. Shortest Unsorted Continuous Subarray
class Solution:
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
is_same=[x==y for x,y in zip(nums,sorted(nums))]
return 0 if all(is_same) else len(nums)-is_same[::-1].index(False)-is_same.index(False)
class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
xixi=''.join(map(str,[0]+flowerbed+[0])).split('1')
return n<=sum([(len(x)-1)//2 for x in xixi if x])
628. Maximum Product of Three Numbers
class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])
643. Maximum Average Subarray I
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
newSum=maxSum=sum(nums[:k])
for i in range(len(nums)-k):
newSum=newSum-nums[i]+nums[I+k]
if newSum>maxSum:
maxSum=newSum
return maxSum/k