自我监督刷题记录处2

自我监督刷题记录处2

第2天,💔…那些刷几千题的人是怎么做到的。。。

Leetcode 4 Median of Two Sorted Arrays

(Hard Level )

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
    	m, n = len(nums1), len(nums2)
	
        if m > n:
            nums1, nums2, m, n = nums2, nums1, n, m

        # 题目给定数组不会同时为空
        if not n:
            raise ValueError("数组长度不同时为零")

       	i_min, i_max = 0, m
       
       	# left集合元素数量,如果m+n是奇数,left比right多一个数据
        count_of_left = (m + n + 1) // 2  

        while i_min <= i_max:
            i = (i_min + i_max) // 2  				# left有i个nums1的元素
            j = count_of_left - i  					# left有j个nums2的元素
            if i > 0 and nums1[i - 1] > nums2[j]:
                i_max = i - 1						# i太大,要减少
            elif i < m and nums1[i] < nums2[j - 1]:
                i_min = i + 1						# i太小,要增加
            else:
                if i == 0:
                    max_of_left = nums2[j - 1]
                elif j == 0:
                    max_of_left = nums1[i - 1]
                else:
                    max_of_left = max(nums1[i - 1], nums2[j - 1])

                if (m + n) % 2:
                    return float(max_of_left)				# 结果是浮点数

                if i == m:
                    min_of_right = nums2[j]
                elif j == n:
                    min_of_right = nums1[i]
                else:
                    min_of_right = min(nums1[i], nums2[j])

                return (max_of_left + min_of_right) / 2.0	


要求时间复杂度在O(log(m+n))所以一定是二分查找。

Leetcode 5 Longest Palindromic Substring

(Medium Level ) 有问题的代码。待解救

class Solution:
    def longestPalindrome(self, s: str) -> str:
		length = len(s)
		
		#先新建个长度计算的方法
        def get_len(l,r):
            while l >=0 and r < length and s[l]==s[r] :
                #l,r分别从中间想两边移动
                l -= 1
                r += 1
            return r - l + 1
        
        start = 0
        len_ = 0
		
		#遍历
        for i in range(length):
			#比较奇偶长度两种情况。
            cur = max(get_len(i,i),get_len(i,i+1))

			#判断是否更新长度
            if cur <= len_:continue
            len_ = cur

			#计算start点
            start = i -(cur -1) //2
        return s[start:start+length] 

代码上传不了,可能有问题。。。。调试时未发现,,什么鬼

Leetcode 7 Reverse Integer

(Easy Level )

class Solution:
    def reverse(self, x: int) -> int:   
    	if x < 0:
    		x = -1 * x
    		x = int('-'+str(x)[::-1])
    	else:
    	 	x = int(str(x)[::-1])
    	 if x > 2**31-1 or x < -2**31:
    	 	return 0
    	 return x
    	

没时间了,偷懒跳着写个简单题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值