# LeetCode 边学python边练算法（持续更新）

## 1、两数之和

nums1 = [1, 3]
nums2 = 2

nums1 = [1, 2]
nums2 = [3, 4]

### 我的代码

``````class Solution:
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
end=0
map = {}
key = 0
for num in nums:
if target-num in map :
key = target-num
break
else:
map[num] = end;
end+=1

start = map[key]
result = [start,end]
return result
``````

• 定义

map = {}

• 遍历

• 存数据
• 取数据

• 定义
• 遍历
• 存数据
• 取数据

## 2、两数相加

### 我的代码

``````# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """
pro = 0
res = ListNode(0)
temp = res
while l1 is not None or l2 is not None :
d1 ,d2 = 0,0
if l1 is not None :
d1 = l1.val
l1 = l1.next
if l2 is not None:
d2 = l2.val
l2 = l2.next
d = d1+d2+pro
pro = d//10
if d>= 10:
temp.val = d-10
else:
temp.val = d
if l1 is not None or l2 is not None:
temp.next = ListNode(0)
temp = temp.next
if pro > 0 :
temp.next = ListNode(pro)
return res
``````

## 3、无重复字符的最长子串

### 我的代码

``````class Solution:
def lengthOfLongestSubstring(self, s):
""" :type s: str :rtype: int """
now = 0
temp = ""
last = 0
maxStr = ""
for c in s:
if c in temp:
last = last + temp.index(c) + 1
temp = s[last:now+1]
if len(temp) > len(maxStr) :
maxStr = temp
now = now+1
return len(maxStr)
``````

## 4、两个排序数组的中位数

nums1 = [1, 3]
nums2 = 2

nums1 = [1, 2]
nums2 = [3, 4]

### 我的代码（未通过 ）

``````class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""" :type nums1: List[int] :type nums2: List[int] :rtype: float """
length = len(nums1) + len(nums2)
start = 1
end = length
i,j,k,t = 0,len(nums1)-1,0,len(nums2)-1
if len(nums1) == 0 or len(nums2) == 0 or nums1 == nums2:
if len(nums1) != 0 and len(nums2) == 0:
temp = nums1
elif len(nums2) != 0 and len(nums1) == 0:
temp = nums2
else:
temp = nums1
length = len(temp)
if length == 1:
return temp[0]
if length % 2 == 0:
return (temp[length//2 - 1] + temp[length//2])/2
else:
return temp[length//2]
else:
while True:
if (length % 2 == 0 and start + 1 == end) or (length % 2 == 1 and start == end):
middle =  nums1[i] + nums1[j] +nums2[k] + nums2[t]
return middle/4
if (nums1[j] >= nums2[t] and j > 0):
j = j-1
end = end-1
if (nums1[j] < nums2[t] and t > 0):
t = t-1
end = end-1
if (nums1[i] >= nums2[k] and k < len(nums2)-1 ):
k = k+1
start = start+1
if (nums1[i] < nums2[k] and i < len(nums1)-1 ):
i = i+1
start = start+1
``````