20201229
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
https://leetcode-cn.com/problems/two-sum/
"""
def twoSum(nums,target):
for i in range(0,len(nums)):
for j in range(0,len(nums)):
if i!=j and nums[i] + nums[j] == target:
return [i,j]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dct = {}
for i, n in enumerate(nums):
cp = target - n
if cp in dct:
return [dct[cp], i]
else:
dct[n] = i
# print(twoSum([3,2,4],6))
print(twoSum_1([2,7,11,15],9))
"""
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
"""
def lengthOfLongestSubstring(s):
# 思路
# 一个s ,存起来,看下一个字符串是不是在我的存货中,有的话取出存货的索引,获取长度
s_len = len(s)
temproary_s = ""
index_l = 0
for index in range(s_len):
if s[index] in temproary_s:
old_s_index = len(temproary_s) - temproary_s.index(s[index])
index_l = index-old_s_index+2 if index-old_s_index+2 > index_l else index_l
temproary_s = s[index] + temproary_s
index_l = index_l if index_l != 0 else s_len
return index_l
下班了,拜拜了
20201230
"""
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
"""
def findMedianSortedArrays(nums1: list, nums2: list):
temporary = sorted(nums1 + nums2, key=lambda x: x, reverse=False)
if temporary:
len_t = len(temporary)
print(temporary)
if len_t % 2 == 0: # 偶数的话
return (temporary[len_t // 2] + temporary[len_t // 2 - 1]) / 2
else:
return temporary[len_t // 2]
else:
return []
"""
变体:先找出两个数组的中位数,合并之后在找出合并数组的中位数
"""
def findMedianSortedArrays_2(nums1: list, nums2: list):
temporary = []
while True:
if temporary:
len_t = len(temporary)
print(temporary)
if len_t % 2 == 0: # 偶数的话
return (temporary[len_t // 2] + temporary[len_t // 2 - 1]) / 2
else:
return temporary[len_t // 2]
len_n1 = len(nums1)
len_n2 = len(nums2)
l_n1 = [nums1[len_n1 // 2], nums1[len_n1 // 2 - 1]] if len_n1 % 2 == 0 and len_n1 > 1 else [
nums1[len_n1 // 2]] if len_n1 != 0 else []
l_n2 = [nums2[len_n2 // 2], nums2[len_n2 // 2 - 1]] if len_n2 % 2 == 0 and len_n2 > 1 else [
nums2[len_n2 // 2]] if len_n2 != 0 else []
temporary = sorted(l_n1 + l_n2, key=lambda x: x, reverse=False)