【LeetCode刷题日记】算法1-9


1. 两数之和

给定一个整数数组nums和一个整数目标值target,请你在该数组中找出 和为目标值target的那两个整数,并返回它们的数组下标。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                sum = nums[i] + nums[j]
                if sum == target:
                    return [i, j]

2. 两数相加(中等)

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。
(小学数学题思想,个位相加,逢10进1)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(0)
        r = result
        carry = 0
        while l1 or l2:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            s = carry + x + y
            carry = s //10 
            r.next = ListNode(s % 10)
            r = r.next
            if (l1!=None):l1=l1.next
            if (l2!=None):l2=l2.next
        if carry>0:
            r.next = ListNode(1)

        return result.next

3. 无重复字符的最长子串(中等)

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

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        max_s = ''
        temp = ''

        for i in s:
            is_same = False
            for j in temp:
                if i == j:
                    is_same = True
                    break
                else:
                    continue
            
            if is_same:
                temp = temp[temp.index(i)+1:] + i
            else:
                temp += i
                if len(temp) >= len(max_s):
                    max_s = temp

        return len(max_s)

4. 寻找两个正序数组的中位数(困难)

给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1nums2。请你找出并返回这两个正序数组的 中位数 。

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        len1 = len(nums1)
        len2 = len(nums2)
        output_id = []
        if (len1 + len2) % 2 == 1:
            output_id.append(int((len1 + len2 - 1) / 2))
        else:
            output_id.append(int((len1 + len2) / 2 - 1))
            output_id.append(int((len1 + len2) / 2))
        
        i,j = 0,0
        all_list = []
        while i < len1 and j < len2:
            if nums1[i] < nums2[j]:
                all_list.append(nums1[i])
                i += 1
            else:
                all_list.append(nums2[j])
                j +=1
        if i >= len1:
            all_list += nums2[j:]
        if j >= len2:
            all_list += nums1[i:]

        result = [all_list[i] for i in output_id]
        re = float(sum(result)) / len(result)

        return re

5. 最长回文子串(中等)

给你一个字符串 s,找到 s 中最长的回文子串。

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        for i in range(len(s), 0, -1):
            for j in range(len(s) - i + 1):
                s_t = s[j: j+i]
                s_t_1 = s_t[::-1]
                if s_t == s_t_1:
                    return s_t

6. Z 字形变换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s

        str_m = [""] * numRows
        id,sum = 0,0
        is_return = 1
        for i in s:
            str_m[id] += i
            id += is_return
            sum += 1
            if sum == numRows-1:
                is_return = -is_return
                sum = 0

        result = ''
        for i in str_m: result += i
        return result

7. 整数反转(中等)

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 2^31 − 1] ,就返回 0。

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0

        x = str(x)
        is_neg = False
        if x[0] == '-':
            is_neg = True
            x = x[1:]

        x = x[::-1]
        result = ''
        for i in range(len(x)):
            if x[i] != '0':
                result = x[i:]
                break
        
        result = -int(result) if is_neg else int(result)

        return result if -2**31 < result < 2**31 - 1 else 0

8. 字符串转换整数 (atoi)(中等)

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。

class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = ''
        isn = 0 # 负号个数
        isp = 0 # 加号个数
        mm = True
        for i in s:
            if mm and i not in "1234567890":
                if i in ' -+':
                    if i == '-': 
                        isn += 1
                        if isn+isp==2:break         # 排除'+-'情况
                    elif i == '+':
                        isp += 1
                        if isn+isp==2:break         
                    elif (isp or isn) and i==' ':   # 排除' + 4'情况
                        break
                else:
                    break
            elif i in "1234567890" or mm:
                result += i
                mm = False
            else:
                break

        result = int(result) if result else 0
        result = -int(result) if isn==1 else int(result)
        result = max(min(result, 2**31-1), -2**31)
        
        return result

9. 回文数

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        is_pp = True
        x = str(x)
        len_x = len(x)

        for i in range(int(len_x/2)):
            if x[i] == x[len_x-i-1]:
                continue
            else:
                is_pp = False
                break

        return is_pp

参考

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems

猜你喜欢

转载自blog.csdn.net/weixin_47691066/article/details/127471946