10.31-11.4 leetcode基于python刷题

10.31-11.4 leetcode基于python刷题

88. Merge Sorted Array(Easy)

'''
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

给你两个整数数组nums1和nums2,按非递减顺序排序,以及两个整数m和n,分别代表nums1和nums2的元素数。
将nums1和nums2合并为一个以非递减顺序排序的数组。
最终排序后的数组不应该由函数返回,而是存储在数组nums1内。为了适应这一点,nums1的长度为m + n,其中前m个元素表示应该被合并的元素,最后n个元素被设置为0,应该被忽略。
'''

思路

此题有个坑,就是在于给出的m,n并不是两个数组的长度,而是每个数组中不为0的元素个数。
我们从两个数组的最后一位开始比较,并将较大的那一位与之对应的第一个列表的最后元素交换(即把最大的元素放到最后)。但我们要考虑到如果第二个列表的长度长于第一个列表的长度,这个时候我们只需要把第二个列表的前面所对应的元素赋值给第一个列表的前面的元素即可。
这题主要要认真读题。

代码实现

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """

        while m > 0 and n > 0:
            if nums1[m-1] < nums2[n-1]:
                nums1[m-1+n] = nums2[n-1]
                n -= 1
            else:
                nums1[m-1+n],nums1[m-1] = nums1[m-1],nums1[m-1+n]
                m -= 1

        if m == 0 and n > 0:
            nums1[:n] = nums2[:n]

        return nums1

s = Solution()
s = s.merge([1,2,3,0,0,0],3,[2,5,6],3)
print(s)

nimg.cn/46d681c7f8674a3eba4de94f7ad5a718.png)

运行速度

在这里插入图片描述

31. Next Permutation(Medium)

'''
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of arr = [1,2,3] is [1,3,2].
Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.

一个整数数组的排列是将其成员排列成一个序列或线性顺序。
例如,对于arr = [1,2,3], 以下是arr的所有排列:[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1] 。
一个整数数组的下一个排列组合是其整数的下一个lexicographically greater permutation。更正式地说,如果该数组的所有排列组合按照其lexicographical顺序在一个容器中排序,那么该数组的下一个排列组合就是在排序的容器中排在它后面的排列组合。如果这样的排列不可能,则必须将该数组重新排列为可能的最低顺序(即按升序排列)。
例如,arr=[1,2,3]的下一个排列是[1,3,2]。
同样地,arr = [2,3,1]的下一个排列是[3,1,2]。
而arr=[3,2,1]的下一个排列是[1,2,3],因为[3,2,1]没有一个较大的列式重排。
给出一个整数nums的数组,找出nums的下一个排列组合。
替换必须到位,并且只使用固定的额外内存。
通过www.DeepL.com/Translator(免费版)翻译
'''

思路

这题的题目给它简单的说一下,就是给你一组数字,去交换两位数字,得到一个最小的比原数字大的数字。
要想得到一个最小的比原数字大的数字,我们肯定是将尽可能低的数位变大,所以如果一个数字是顺序的(例如321),这样就不好得到结果,因为已经是最大值了。所以从数字的低位开始,一旦出现非降序排列的数字,我们就找到了需要交换的数位。
那么我们该和谁交换呢,首先,要比这个数字大,但是还要尽可能的小。其实就是所有这个数位之后的数字中最小且比这个数字大的数字,交换以后,还需要把这一部分变成倒序,因为倒序才更小,因为此时已经保证了高位比之前的大,所以要把后面的变得尽可能的小。

代码实现

class Solution(object):
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """

        if sorted(nums, reverse=True) == nums:
            nums.reverse()
            return nums

        for i in range(len(nums) - 1, 0, -1):
            if nums[i - 1] >= nums[i]:
                continue
            else:
                left = i-1
                min = nums[i]
                right = i

                for k in range(i,len(nums)):
                    if nums[k] <= min and nums[k] > nums[left]:
                        min = nums[k]
                        right = k
                break

        nums[left], nums[right] = nums[right], nums[left]
        nums[left + 1:] = nums[left + 1:][::-1]

        return nums

s = Solution()
s = s.nextPermutation([1,2,3])
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

17. Letter Combinations of a Phone Number(Medium)

'''
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

给出一个包含2-9数字的字符串,返回该数字可能代表的所有字母组合。以任何顺序返回答案。
下面给出了一个数字与字母的映射(就像电话按钮上的一样)。请注意,1并没有映射到任何字母。
'''

在这里插入图片描述

思路

事实上就是一个多层循环的事情,最外层循环是遍历所有需要转换的数字,然后找到每个数字所对应的字母,再对结果中的每一个结果进行遍历,每个结果加上每个数字所对应的字母。

代码实现

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """

        if len(digits) == 0:
            return []

        dic = {
            2:'abc',
            3:'def',
            4:'ghi',
            5:'jkl',
            6:'mno',
            7:'pqrs',
            8:'tuv',
            9:'wxyz'
        }

        res = ['']

        for digit in digits:
            temp_list = []
            for item in dic[int(digit)]:
                for result in res:
                    temp_list.append(result + item)
            res = temp_list

        return res

s = Solution()
s = s.letterCombinations("23")
print(s)

运行速度

在这里插入图片描述

22. Generate Parentheses(Medium)

'''
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

给出n对小括号,写一个函数来生成所有格式良好的小括号的组合。
'''

思路

只需搞清楚,只要(的个数<n,就可以加(,而加)的条件是right < left ,输出的条件是left == n and right == n

代码实现

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """

        def ff(n,left,right,res,s):
            if right > left:
                return
            if left == n and right == n:
                res.append(s)
                return
            if left < n:
                ff(n,left+1,right,res,s+'(')
            if right < left:
                ff(n,left, right+1, res, s+')')
            return res

        res = []
        ff(n,0,0,res,'')
        return res

s = Solution()
s = s.generateParenthesis(3)
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

125. Valid Palindrome(Easy)

'''
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.

如果在将所有大写字母转换为小写字母并去除所有非字母数字字符后,一个短语向前和向后读起来都是一样的,那么它就是一个回文。字母数字字符包括字母和数字。
给定一个字符串s,如果它是一个回文,返回true,否则返回false。
'''

思路

直接判断后看是否与逆序相等就好

代码实现

class Solution2(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s= [x for x in s.lower() if x.isalnum()]
        return s==s[::-1]

s = Solution()
s = s.isPalindrome("A man, a plan, a canal: Panama")
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

108. Convert Sorted Array to Binary Search Tree(Easy)

'''
Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.\

给出一个元素按升序排序的整数数组nums,将其转换为高度平衡的二进制搜索树。
'''

思路

这还是个递归问题,每一次的根节点都是中间的数字,然后去mid的左边去找左节点,右边去找右节点

代码实现

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """

       class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """

        if not nums:
            return None
        mid = len(nums) // 2
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        return root

运行速度

在这里插入图片描述

33. Search in Rotated Sorted Array(Medium)

'''
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.

有一个按升序排序的整数数组nums(有不同的值)。
在传递给你的函数之前,nums可能在一个未知的枢轴索引k(1 <= k < nums.length)处被旋转,这样得到的数组是[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1] (0-索引)。例如,[0,1,2,4,5,6,7]可能在枢轴索引3处被旋转,成为[4,5,6,7,0,1,2]。
给出可能旋转后的数组nums和一个整数目标,如果目标在nums中,则返回目标的索引,如果不在nums中则返回-1。
你必须写一个运行时间复杂度为O(log n)的算法。
'''

思路

这个题目说明白了,就是说一组数字,分成两段,每一段都是有顺序的,去进行查找。根据题目要求,我们肯定是不能将这组数字进行一次遍历,所以我们可以采用二分查找的思路。
将target与mid所对应的值进行比较,来确定target是在左边有序还是右边有序,然后再进行二分查找。等号需要注意

代码实现

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """

        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] == target:
                return mid

            if nums[left] <= nums[mid]:
                if nums[left] <= target and target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            else:
                if nums[mid] < target and target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        return -1

s = Solution()
s = s.search(nums = [4,5,6,7,0,1,2], target = 0)
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值