11.7- 11.11leetcode基于python刷题

11.7-11.11 leetcode基于python刷题

21. Merge Two Sorted Lists(Easy)

'''
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.

你得到了两个排序的链表list1和list2的头。
将这两个列表合并为一个排序的列表。这个列表应该是由前两个列表的节点拼接而成的。
返回合并后的链表的头部。
'''

思路

每次两个list的val比较大小,小的那个存入curr并且向后移动一位,但还有考虑的是两个list不等长,所以最后要把多出来的那部分放入链表中。

代码运行

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """

        curr = dummy = ListNode(0)

        while list1 and list2:
            if list1.val < list2.val:
                curr.next = list1
                list1 = list1.next
            else:
                curr.next = list2
                list2 = list2.next
            curr = curr.next
        curr.next = list1 or list2
        return dummy.next

运行速度

在这里插入图片描述

34. Find First and Last Position of Element in Sorted Array(Medium)

'''
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.

给定一个按非递减顺序排序的整数nums数组,找出给定目标值的开始和结束位置。
如果在数组中没有找到目标值,返回[-1, -1]。
你必须写一个运行时间复杂度为O(log n)的算法。
'''

思路

第一次出现的下标很好找。就是用内置函数.index(),去找最后一次出现的下标,事实上就是列表放过来后的第一次出现的位置。

代码实现

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

        if target not in nums:
            return [-1,-1]
        start = nums.index(target)
        finish = len(nums) - 1 -nums[::-1].index(target)

        return [start,finish]

s2 = Solution2()
s2 = s2.searchRange([5,7,7,8,8,10],8)
print(s2)

在这里插入图片描述

运行速度

在这里插入图片描述

168. Excel Sheet Column Title(Easy)

'''
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

给出一个整数columnNumber,返回它在Excel表格中出现的相应列的标题。
'''

思路

思路1.类似于十进制的获取,每次整除26,取余,利用ASCII码转换成字母,需要注意,每次余数为0时,其实是Z,所以不能用ASCII转换
思路2.建立一个26字母的字典进行转换

代码实现

class Solution(object):
    def convertToTitle(self, columnNumber):
        """
        :type columnNumber: int
        :rtype: str
        """

        res = ''

        while columnNumber > 0:
            temp = columnNumber % 26
            if temp:
                res += str(chr(temp+64))
            else:
                res += 'Z'
            if columnNumber % 26 == 0:
                columnNumber = columnNumber // 26 - 1
            else:
                columnNumber = columnNumber // 26

        return res[::-1]

s = Solution()
s = s.convertToTitle(1)
print(s)

class Solution2:
    def convertToTitle(self, n: int) -> str:
        dic = {1: 'A',
               2: 'B',
               3: 'C',
               4: 'D',
               5: 'E',
               6: 'F',
               7: 'G',
               8: 'H',
               9: 'I',
               10: 'J',
               11: 'K',
               12: 'L',
               13: 'M',
               14: 'N',
               15: 'O',
               16: 'P',
               17: 'Q',
               18: 'R',
               19: 'S',
               20: 'T',
               21: 'U',
               22: 'V',
               23: 'W',
               24: 'X',
               25: 'Y',
               26: 'Z',
               }
        res = ''
        while n > 26:
            count = n % 26
            if count == 0:
                count = 26
                res += dic[count]
                n = n // 26 - 1
            else:
                res += dic[count]
                n = n // 26
        res += dic[n]
        res = res[::-1]
        return res

s2 = Solution2()
s2 = s2.convertToTitle(1)
print(s2)

在这里插入图片描述

运行速度

在这里插入图片描述

28. Find the Index of the First Occurrence in a String(Medium)

'''
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

给出两个字符串 needle 和 haystack,返回 haystack 中第一次出现的 needle 的索引,如果 needle 不是 haystack 的一部分,则返回 -1。
'''

思路

依次往后找就OK了

代码实现

class Solution(object):
    def strStr(self, haystack, needle):
        len1 = len(haystack)
        len2 = len(needle)

        if len1 < len2:
            return -1
        for i in range(len1 - len2+2):
            if i == len1 - len2+1:
                return -1
            if haystack[i:i+len2] == needle:
                return i

s = Solution()
s = s.strStr(haystack = "leetcode", needle = "leeto")
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

36. Valid Sudoku(Medium)

'''
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.

判断一个9×9的数独棋盘是否有效。只有填充的单元格需要根据以下规则进行验证。
每一行必须包含数字1-9而不重复。
每一列必须包含数字1-9,没有重复。
网格的9个3 x 3的子箱中的每一个都必须包含数字1-9,且不重复。
注意。
一个数独棋盘(部分填充)可能是有效的,但不一定是可解的。
只有填满的单元格才需要根据上述规则进行验证。
'''

思路

首先对每一行和每一列进行检验,‘.’要做特殊处理。
随后对3×3的矩阵进行检验,其中在temp中可进行枚举,或者弄个循环也可以。

代码实现

class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in range(9):
            temp_hang = []
            temp_lie = []
            for item in board[i]:
                if item in temp_hang and item != '.':
                    return False
                else:
                    temp_hang.append(item)
            for item in (a[i] for a in board):
                if item in temp_lie and item != '.':
                    return False
                else:
                    temp_lie.append(item)

        for k in range(0,7,3):
            for j in range(0,7,3):
                temp = [board[k][j],board[k][j+1],board[k][j+2],
                        board[k+1][j],board[k+1][j+1],board[k+1][j+2],
                        board[k+2][j],board[k+2][j+1],board[k+2][j+2]]
                list = []
                for item in temp:
                    if item in list and item != '.':
                        return False
                    else:
                        list.append(item)
        return True

s = Solution()
s = s.isValidSudoku([["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]])
print(s)

在这里插入图片描述

运行速度

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值