目录
- 两数之和
- 和为 K 的子数组
- 三数之和
- 两数相加【链表】
- 我的半路答案:没有看到是链表
- 在b站up那里学到的【复写失败后整理】
两数之和
我的答案
class Solution(object):def twoSum(self, nums, target):leng=len(nums)for i in range(leng):for j in range(leng):if nums[i]+nums[j]==target and i!=j:return [i,j]
在b站up那里学到的【然后自己复写】
- 忘记怎么取list的第二个值了。【利用range的特性】
class Solution(object):def twoSum(self, nums, target):leng=len(nums)for i in range(0,leng):for j in range(i+1,leng):if nums[i]+nums[j]==target and i!=j:return [i,j]
class Solution(object):def twoSum(self, nums, target):mapping = {}for i in range(0, len(nums)):mapping[nums[i]] = ifor j in range(0, len(nums)):diff = target - nums[j]if (diff in mapping and mapping[diff] != j):return [j,mapping[diff]];
和为 K 的子数组
在b站up那里学到的【然后自己复写】
class Solution(object):def subarraySum(self, nums, k):count = 0dic={}dic[0] = 1cur_sum = 0for num in nums:cur_sum = cur_sum + numif cur_sum-k in dic:count=count+dic[cur_sum-k]if cur_sum in dic:dic[cur_sum] +=1else:dic[cur_sum] = 1return count
三数之和
在b站up那里学到的【然后自己复写】
class Solution(object):def threeSum(self, nums):resol=[]nums.sort()for i in range(len(nums)):cur = iif nums[cur]>0:return resolif cur>0 and nums[cur-1] == nums[cur]:continue left = cur+1right = len(nums)-1while left<right:total = nums[cur]+nums[left]+nums[right]if total >0:right-=1elif total<0:left+=1else:resol.append([nums[cur],nums[left],nums[right]])while left<right and nums[right-1]==nums[right]:right-=1while left<right and nums[left+1]==nums[left]:left+=1right-=1left+=1 return resol
两数相加【链表】
我的半路答案:没有看到是链表
- 我还没有写完,只是想半路测一下是否正确。
- 关于链表的话,我相对还是弱一点,下次巩固。
class Solution(object):def addTwoNumbers(self, l1, l2):resl=[]cur=0len1=len(l1)len2=len(l2)for i in range(min(len1,len2)):total=l1[i]+l2[i]+curif total>10:cur=total/10resl.append(total%10)else:resl.append(total)return resl
在b站up那里学到的【复写失败后整理】
class Solution(object):def addTwoNumbers(self, l1, l2):total = 0next1 = 0dummy = ListNode()cur = dummywhile (l1 != None and l2 != None):total = l1.val + l2.val + next1cur.next = ListNode(total % 10)next1 = total // 10cur = cur.nextl1 = l1.nextl2 = l2.nextwhile l1 != None:total = l1.val + next1cur.next = ListNode(total % 10)next1 = total // 10cur = cur.nextl1 = l1.nextwhile l2 != None:total = l2.val + next1cur.next = ListNode(total % 10)next1 = total // 10cur = cur.nextl2 = l2.nextif next1 != 0:cur.next = ListNode(next1)return dummy.next