第八周python作业:LeetCode 训练题

1、两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        self.nums = nums
        self.target = target
        l = len(self.nums)
        for i in range(0,l):
            a = target-self.nums[i]
            if a in self.nums:
                b = self.nums.index(a)
                if i!=b:
                    return i,b
                else:
                    continue


2、两个排序数组的中位数

给定两个大小为 m n 的有序数组 nums1  nums2 

请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n))


示例 1:

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

中位数是 2.0

示例 2:

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

中位数是 (2 + 3)/2 = 2.5


代码:

class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        l = len(nums1)+len(nums2)
        num = []

        while nums1 and nums2:
	        if nums1[0]<nums2[0]:
		        num.append(nums1.pop(0))
	        else:
		        num.append(nums2.pop(0))

        if nums1:
	        num+=nums1
        else :
	        num+=nums2

        if l%2==0:
	        mid = (num[int(l/2)-1]+num[int(l/2)])/2
        else:
	        mid = num[int(l/2)]
        return mid


3. 无重复字符的最长子串

给定一个字符串,找出不含有重复字符的最长子串的长度。

示例:

给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。

给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。

给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串"pwke" 是 子序列  而不是子串。

代码:

class Solution:
	def lengthOfLongestSubstring(self, s):
		max_num = 0
		ll=len(s)
		for i in range(0,ll):
			l=0
			s1=""
			for j in range(i,len(s)):
				if s[j] in s1:
					break
				else:
					s1+=s[j]
					l+=1
			if l>max_num:
				max_num = l
		return max_num



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值