leetcode刷题_Python(11-20)

本文精选LeetCode上的经典算法题目,包括括号生成、搜索插入位置、计数与说、最大子数组和、最后单词长度、加一、二进制求和、平方根、爬楼梯、删除排序链表中的重复项等,详细解析了每道题目的解题思路与代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继续看视频刷题!!
https://www.bilibili.com/video/av45844036

11.第22题(中等):Generate Parentheses
Given n pairs of parentheses,
write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

解题思路:要用到递归的思想。注意,都是由左括号开始的。然后当右括号数目大于左括号时,代表错误。(但题目中的l,r代表的是剩下的括号,所以r<l 错误)
在这里插入图片描述
代码:

class Solution:
    def generateParenthesis(self, n):
        if n == 0:
            return []
        result = []
        self.generateProcess(n, n, '', result)
        return result
    def generateProcess(self, l, r, item, result):   
        if r < l:
             return
        if l ==0 and r ==0:
            result.append(item)
        if l > 0 :
            self.generateProcess(l-1, r, item+'(', result)
        if r > 0 :
            self.generateProcess(l, r-1, item+')', result)
  1. 第35题(简单):Search Insert Position
    Given a sorted array and a target value, return the index if the target is found.
    If not, return the index where it would be if it were inserted in order.
    (1)Example 1:
    Input: [1,3,5,6], 5
    Output: 2
    (2)Example 2:
    Input: [1,3,5,6], 2
    Output: 1
    (3)Example 3:
    Input: [1,3,5,6], 7
    Output: 4
    (4)Example 4:
    Input: [1,3,5,6], 0
    Output: 0

代码:

class Solution:
    def searchInsert(self, nums, target):
        if target > nums[-1]:
            return len(nums)
        for i in range(len(nums)):
            if nums[i] >= target:
                return i 
  1. 第38题(简单):Count and Say
    The count-and-say sequence is the sequence of integers with the first five terms as following:
    在这里插入图片描述
    1 is read off as “one 1” or 11.
    11 is read off as “two 1s” or 21.
    21 is read off as “one 2, then one 1” or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

(1) Example 1:
Input: 1
Output: “1”
(2) Example 2:
Input: 4
Output: “1211”

代码:

class Solution:
    def countAndSay(self, n):
        seq = "1"
        for i in range(n-1):
            seq = self.getNext(seq)
        return seq
    
    def getNext(self, seq):
        i = 0
        next_seq = ""
        while i < len(seq):
            count = 1
            while i < len(seq)-1 and seq[i] == seq[i+1]:
                count += 1
                i += 1
            next_seq += str(count) + seq[i]
            i += 1
        return next_seq
  1. 第53题:Maximum Subarray (简单):连续子数组的最大和问题
    Given an integer array nums, find the contiguous subarray
    (containing at least one number) ,which has the largest sum and return its sum.
    题目描述:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
    Example:
    Input: [-2,1,-3,4,-1,2,1,-5,4],
    Output: 6
    Explanation: [4,-1,2,1] has the largest sum = 6.
    主要思想:就是找到一个局部最大值,和全局最大值。

代码:

class Solution:
    def maxSubArray(self, nums):
        if max(nums) < 0:
            return max(nums)
        #如果都是负数,则最大的数也是负数,直接返回这个最大数
        local_max, global_max = 0, 0
        for num in nums:
            local_max = max(0, local_max + num) 
            global_max = max(global_max, local_max)
        return global_max
  1. 第58题(简单):Length of Last Words
    Given a strings consists of upper/lower-case alphabets and empty space characters ’ ',
    return the length of last word in the string.
    If the last word does not exist, return 0.
    (给定一个字符串,字符串中包含空格和单词,计算最后一个单词的长度。)
    Example:
    Input: “Hello World”
    Output: 5

代码:

class Solution:
    def lengthOfLastWord(self, s) :
        count = 0
        local_count = 0   
        for i in range(len(s)):
            if s[i] == " ":
                local_count = 0
            else:
                local_count += 1
                count = local_count        
        return count
  1. 第66题:Plus One 简单
    Given a non-empty array of digits representing a non-negative integer,
    plus one to the integer.
    (1)Example 1:
    Input: [1,2,3]
    Output: [1,2,4]
    Explanation: The array represents the integer 123.
    (2)Example 2:
    Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: The array represents the integer 4321.

代码:

class Solution:
    def plusOne(self, digits):
        for i in reversed(range(len(digits))):
            if digits[i] == 9:
                digits[i] = 0
            else:
                digits[i] += 1
                return digits
        digits[0] = 1
        digits.append(0)
        return digits   
  1. 第67题:(简单):Add Binary
    Given two binary strings, return their sum (also a binary string).
    The input strings are both non-empty and contains only characters 1 or 0.
    给定两个二进制字符串,返回他们的和(用二进制表示)。
    输入为非空字符串且只包含数字 1 和 0。
    (二进制计算:1+1 = 10,1+1+1 = 11)
    Example 1:
    Input: a = “11”, b = “1”
    Output: “100”

Example 2:
Input: a = “1010”, b = “1011”
Output: “10101”

class Solution:
    def addBinary(self, a, b) :
        result, carry, val = "", 0, 0
        for i in range(max(len(a),len(b))):
            val = carry
            if i < len(a):
                val += int(a[-(1+i)])
            if i < len(b):
                val += int(b[-(1+i)])
            carry, val = int(val/2), val % 2
            result += str(val)
        if carry:
            result += str(1)
        return result[::-1]
  1. 第69题(简单):Sqrt(x)
    实现 int sqrt(int x) 函数。 计算并返回 x 的平方根。 x 保证是一个非负整数。
    (1)Example 1:
    Input: 4
    Output: 2
    (2)Example 2:
    Input: 8
    Output: 2
    Explanation: The square root of 8 is 2.82842…, and since the decimal part is truncated, 2 is returned.

基本思路:运用二分法的思想。
代码:

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 2:
            return x
        left, right  = 1, x // 2
        while left <= right:
            mid = left + (right-left) // 2
            if mid == x/mid:
                return mid
            elif mid > x/mid:
                right = mid -1
            else:
                left = mid + 1
        return left -1
  1. 第70题(简单): Climbing Stairs
    You are climbing a stair case. It takes n steps to reach to the top.
    Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
    Note: Given n will be a positive integer.
    (1) Example 1:
    Input: 2
    Output: 2
    Explanation: There are two ways to climb to the top.
    1: 1 step + 1 step
    2: 2 steps
    (2) Example 2:
    Input: 3
    Output: 3
    Explanation: There are three ways to climb to the top.
    1: 1 step + 1 step + 1 step
    2: 1 step + 2 steps
    3: 2 steps + 1 step

主要思想:斐波那契数列 。F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)
在本题中:
n(1) = 1;
n(2) = 2;
n(3) = 3;
n(4) = 5;
n(5) = 8 ;
符合斐波拉契数列。

代码:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        prev, current  = 0, 1
        for i in range(n):
            prev, current = current, prev + current
        return current 
  1. 第83题(简单):Remove Duplicates from Sorted List
    Given a sorted linked list, delete all duplicates such that each element appear only once.
    (1) Example 1:
    Input: 1->1->2
    Output: 1->2
    (2) Example 2
    Input: 1->1->2->3->3
    Output: 1->2->3

代码:

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

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur:
            runner = cur.next
            while runner and cur.val == runner.val:
                runner = runner.next
            cur.next = runner
            cur = runner
        return head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值