每月100题!Python对上Leetcode(简单难度)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38358305/article/details/88319317

1. 两数之和​​​

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

思路:建立字典。时间复杂度o(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for index,value in enumerate(nums):
            sub = target - value
            if sub in dic.keys():
                return[dic[sub],index]
            else:
                dic[value] = index
        return []

7. 整数反转

题目:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

思路:过

class Solution:
    def reverse(self, x: int) -> int:
        y=x if x>0 else -x
        z = 0
        while y:
            z = z*10+y%10
            y //= 10
        z=z if x>0 else -z
        if z>=2**31 or z<-2**31:
            return 0
        else:
            return z

9. 回文数

题目:判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

思路: 首先得到给出的x是一个几位数,然后每次判断当前x的第一位和最后一位是否相同,最后去掉x的前后两位,继续判断。

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            return False
        n = 1
        while x//n>=10:
            n *=10
        while x:
            left = x//n
            right = x%10
            if left != right:
                return False
            x = x%n//10
            n/=100
        return True

13. 罗马数字转整数

题目:给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

思路:用字典转换罗马数,用大数左边的数只有一个来判断+还是-。

class Solution:
    def romanToInt(self, s):
        map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        num, pre = 0, 1000
        for i in [map[j] for j in s]:
            num, pre = num + i - 2 * pre if i > pre else num + i, i
        return num

14. 最长公共前缀

题目:编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""

思路:先找最短的字符串(肯定大于等于最长公共),再遍历比较后面的字符。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        if len(strs) == 1:
            return strs[0]
        minlen = min([len(x) for x in strs])
        end = 0
        while end < minlen:
            for i in range(1,len(strs)):
                if strs[i][end]!= strs[i-1][end]:
                    return strs[0][:end]
            end += 1
        return strs[0][:end]

20. 有效的括号

题目:给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
class Solution:
    def isValid(self, s: str) -> bool:
        a = ['[]','{}','()']
        ls = []
        for i in s:
            ls.append(i)
            if len(ls)>=2 and (ls[-2]+ls[-1]) in a:
                ls = ls[:-2]
        return len(ls) == 0

21. 合并两个有序链表

题目:将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        node = ListNode(2009)
        beg = node
        while l1 and l2:
            if l1.val <= l2.val:
                node.next = l1
                l1 = l1.next
            else:
                node.next = l2
                l2 = l2.next
            node = node.next
        if l1:
            node.next = l1
        else:
            node.next = l2
        return beg.next

 26. 删除排序数组中的重复项

题目:给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        a = nums[0]
        i = 1
        while i <len(nums):
            if a != nums[i]:
                a = nums[i]
                i +=1
            else:
                nums.pop(i)
        return len(nums)

27. 移除元素

给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        while i <len(nums):
            if nums[i] == val:
                nums.pop(i)
            else:
                i+=1
        return len(nums)

 28. 实现strStr()

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle == '':
            return 0
        if needle not in haystack:
            return -1
        l = len(needle)
        i = 0
        while i < len(haystack):
            if haystack[i:i+l] == needle:
                return i
            i+=1
        return -1

猜你喜欢

转载自blog.csdn.net/qq_38358305/article/details/88319317