【代码】LeetCode刷题Python版

python版LeetCode
算法部分


811. 子域名访问计数
class Solution:
    def subdomainVisits(self, cpdomains):
        """
        :type cpdomains: List[str]
        :rtype: List[str]
        """
        topdomain = dict()
        seconddomain = dict()
        thirddomain = dict()
        # 创建各三级域名和访问计数的键值对
        for cpd in cpdomains:
            domain = cpd.split()[1]
            if len(domain.split('.')) == 2:
                topdomain[domain.split('.')[1]] = 0
                seconddomain['.'.join(domain.split('.')[:])] = 0
            if len(domain.split('.')) == 3:
                topdomain[domain.split('.')[2]] = 0
                seconddomain['.'.join(domain.split('.')[1:])] = 0
                thirddomain['.'.join(domain.split('.')[:])] = 0
        # 进行访问计数
        for cpd in cpdomains:
            count = int(cpd.split()[0])
            domain = cpd.split()[1]
            for top in topdomain:
                if domain.endswith(top):
                    topdomain[top] += count
            for second in seconddomain:
                if domain.endswith(second):
                    seconddomain[second] += count
            for third in thirddomain:
                if domain.endswith(third):
                    thirddomain[third] += count

        return [str(c) + ' ' + d for d, c in topdomain.items()] + \
               [str(c) + ' ' + d for d, c in seconddomain.items()] + \
               [str(c) + ' ' + d for d, c in thirddomain.items()]



709. 转换成小写字母
class Solution:
    def toLowerCase(self, str):
        """
        :type str: str
        :rtype: str
        """
        return str.lower()
        


557. 反转字符串中的单词 III      
class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        ls = s.split()
        for i in range(len(ls)):
            ls[i] = ls[i][::-1]
        return ' '.join(ls)



414. 第三大的数
class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        min_nums = min(nums)
        first = min_nums
        second = min_nums
        third = min_nums
        for n in nums:
            if first < n:
                first = n
        for n in nums:
            if n < first and second < n:
                second = n
        for n in nums:
            if n < second and third < n:
                third = n

        if second == third:
            return first
        else:
            return third



344. 反转字符串
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]
        
        
  
231. 2的幂        
class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return bin(n).startswith('0b1') and bin(n).count('1') == 1



217. 存在重复元素
class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(list(set(nums))) != len(nums)



169. 求众数
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in set(nums):
            if nums.count(i) > len(nums)/2:
                return i



136. 只出现一次的数字
class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        num = 0
        for i in nums:
            num = num ^ i
        return num



88. 合并两个有序数组
class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        # a = 0
        # b = 0
        # # nums1中的0真折腾,暂时未解决
        # if nums1[0]==0 and m == 0:
        #     nums1[:] = nums2[:]
        # else:
        #     while b < n and a < m+n:
        #         if nums1[a] > nums2[b]:
        #             nums1[a:a] = [nums2[b]]
        #             b += 1
        #         elif nums1[a] == 0 and nums1[a-1] > 0:
        #             nums1[a:] = nums2[b:]
        #             break
        #         a += 1
        # # 去掉nums1结尾的0
        # while not nums1[-1]:
        #     nums1.pop()
        for i in range(n):
            nums1[m] = nums2[i]
            m += 1
        nums1.sort()



70. 爬楼梯
class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        way = [0, 1, 2]
        for i in range(3, n + 1):
            way.append(way[i - 1] + way[i - 2])
        return way[n]



26. 删除排序数组中的重复项
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # a慢指针, b快指针
        a = 0
        b = 0
        for i in range(len(nums)):
            # 如果快慢不同,则慢指针后移,再赋快指针的值
            if nums[a] != nums[b]:
                a += 1
                nums[a] = nums[b]
            # 快指针从头移动到尾
            b += 1
        # 如果数组为[]返回0
        return a+1 if nums else 0



20. 有效的括号
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        d = {'(': ')', '[': ']', '{': '}'}
        ls = []
        for ss in s:
            if not ls:
                ls.append(ss)
            else:
                if d.get(ls[-1]) == ss:
                    ls.pop()
                else:
                    ls.append(ss)
        return False if ls else True



14. 最长公共前缀
class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        # 如果含有''
        if not strs or '' in strs:
            return ''
        # 按照字符串长度排序,看来是没必要的,
        # strs = sorted(strs, key=lambda s:len(s))
        # 只要找到最短的字符串中的字符,作为暂定的前缀进行判断即可
        prefix = strs[0]
        for s in strs:
            if len(prefix) > len(s):
                prefix = s
        # 切片位置初置为-1
        n = -1
        for i in range(len(prefix)):
            # 如果前缀字符是所有字符串的公共前缀,则切片位置为i,继续判断下一个字符是否匹配
            if all([prefix[i] == s[i] for s in strs]) :
                n = i
            # 否则就找到了最长前缀,退出循环
            else:
                break
        # 如果切片值为-1,则返回'',否则返回从最短的字符串切好的片作为最长公共前缀
        return prefix[:n+1]




9. 回文数
class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        x = str(x)
        return x == x[::-1]
        
        
        
7. 整数反转
class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x < 0:
            # 去掉'-'
            x = '-' + str(x)[1:][::-1]
        elif x > 0:
            x = str(x)
            # 去掉结尾的0
            while x.endswith('0'):
                x = x[:-1]
            x = x[::-1]
        else:
            x = '0'
        # 如果x反转后溢出,或者x==0,那么就返回 0。
        x = int(x)
        if x < -2 ** 31 or x > 2 ** 31 - 1 or x == 0:
            return 0
        return x
        
        
        
771. 宝石与石头
class Solution:
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        n = 0
        for j in J:
            n += S.count(j)
        return n
            
            
            
657. 机器人能否返回原点
class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        return False if (moves.count('R') - moves.count('L')) or (moves.count('U') - moves.count('D')) else True
     
     
        
        
832. 翻转图像
class Solution:
    def flipAndInvertImage(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        for i in range(len(A)):
            A[i] = A[i][::-1]
            for j in range(len(A[i])):
                A[i][j] = int(not A[i][j])
        return A

      
        

476. 数字的补数
class Solution:
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        num = bin(num)
        cpl = list('0b')
        for i in num[2:]:
            if i == '1':
                cpl.append('0')
            else:
                cpl.append('1')
        return int(''.join(cpl), 2)




852. 山脉数组的峰顶索引
class Solution:
    def peakIndexInMountainArray(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        return A.index(max(A))
        



500. 键盘行
class Solution:
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        tab = 'qwertyuiop'
        capslock = 'asdfghjkl'
        shift = 'zxcvbnm'
        inline = []
        for W in words:
            w = W.lower()
            if all(c in tab for c in w) or all(c in capslock for c in w) or all(c in shift for c in w):
                inline.append(W)
        return inline        
               
            


867. 转置矩阵
class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        
        return [[row[col] for row in A] for col in range(len(A[0]))]
        
      
        

349. 两个数组的交集
class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1) & set(nums2))




680. 验证回文字符串 Ⅱ
class Solution:
    def validPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l = 0
        r = len(s) - 1
        while l < r:
            if s[l] != s[r]:
                # 尝试跳过一个字符,直接调用判断接口,去判断剩下的即可
                def judge(s, i, j):
                    while i < j:
                        if s[i] != s[j]:
                            return False
                        i += 1
                        j -= 1
                    return True
                return judge(s, l+1, r) or judge(s, l, r-1)
            l += 1
            r -= 1
        return True




836. 矩形重叠
class Solution:
    def isRectangleOverlap(self, rec1, rec2):
        """
        :type rec1: List[int]
        :type rec2: List[int]
        :rtype: bool
        """    
        
        # rec1中扫描区间
        # 扫描精度prec,步长prec*区间长度
        x = (rec1[3]-rec1[1])
        y = (rec1[2]-rec1[0])
        prec = 1
        
        # 似乎最高精度设置为1/16即可通过测试
        PREC = 1/16
        while prec > PREC:
            i = rec1[0]
            while i < rec1[2]:
                j = rec1[1]
                while j < rec1[3]:
                    if i > rec2[0] and i < rec2[2] and j > rec2[
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: LeetCode 是一个在线编程挑战网站,提供了许多算法和数据结构题目供程序员练习和提高。下面是一些关于使用 Python LeetCode 的提示: 1. 首先,了解题目的要求和限制,并确定解题思路。 2. 使用自己熟悉的编程语言(如 Python)进行编码。 3. 在完成编码后,进行单元测试,确保代码的正确性。 4. 提交代码,查看结果。如果错误,请思考错误原因并进行调试。 5. 反复做题,提高自己的算法和数据结构能力。 6. 可以参考其他人的题解和代码,可以更好的学习和了解题目的解法。 ### 回答2: LeetCode是一款非常好的刷题平台,它提供了大量的算法题目,帮助程序员们提高编程技能。但是,想要LeetCode需要一些方法和技巧。本篇文章主要介绍LeetCode刷题指南,特别是使用Python语言刷题。 首先,我们需要明确一个问题:LeetCode最重要的是什么?我认为是“理解算法”。很多人最开始LeetCode时会想直接写代码试试,这是错误的做法。我们首先需要理解题目的意思,思考算法的解题思路,以及算法的时间复杂度和空间复杂度等问题。只有当我们弄懂了算法的思路,才能够写出高质量的代码。 其次,我们需要建立良好的代码习惯。Python是一门非常简洁优雅的语言,但是我们需要注意代码的可读性和规范性,这样在后期维护代码时会更加方便。建议使用pycharm等IDE工具,并安装Pylint等插件进行代码检查和优化。 接下来,我们需要准备好一些有效的刷题工具。为了方便,我们可以在本地安装刷题必备工具,例如:leetcode-cli、leetcode vscode插件、leetcode-cn的官方Python SDK等。这些工具可以帮助我们快速地创建、调试和提交题解,并且可以方便地查看题目和测试样例。另外,我们还可以用一些在线的工具,如Jupyter Notebook、Google Colab等来刷题。 最后,我们需要保持耐心和持之以恒的心态。LeetCode刷题不是一蹴而就的事情,需要坚持不懈地努力。每道题都应该认真思考,从简单到复杂、从容易到难以深入理解,跟着题目一步步实现代码解题。通过刷题,我们可以锻炼自己的编程技能、提高算法水平、积累自己的编程经验。 总之,LeetCode是一款非常优秀的算法题目平台,它可以帮助程序员们提高编程水平。使用Python语言刷题,需要我们掌握好编程思路,建立好良好的代码习惯,使用好刷题工具,并坚持不懈地刷题去提升自己的能力。 ### 回答3: 随着人工智能和大数据技术的快速发展,编程成为了一项越来越重要的技能。而leetcode算法题是提高编程技能、增加算法思维的有力方式之一。本文主要介绍如何通过Python语言leetcode算法题。 一、准备工作 1.安装Python环境 Python是一种优秀的面向对象的解释型计算机程序设计语言,在如今的人工智能和数据科学领域应用广泛。首先需要安装Python环境,推荐安装本为Python 3.x。 2.注册LeetCode账号 可以通过该网站进行LeetCode算法题刷题,而注册账号是必选步骤。 二、解题流程 1.题目分析:初学者可先从LeetCode官方题解中找到简单难度的题目,通过阅读题目,明确题目的意义,梳理解题思路和关键信息。 2.思路整理:理清题目后,可以尝试使用笔和纸来将题目要求和信息进行抽象和总结。可以画图或列出清晰的步骤,为编写代码提供思路。 3.编写代码:将思路转化为代码实现。结合算法,通过Python语言的面向对象编程,从而完成代码的编写。 4.测试和优化:在完成编码后,需要对代码进行测试,并对代码进行优化处理。可以通过LeetCode的自动评测系统,检查代码运行是否正确。此步骤也有助于人为地检查代码中的错误,提高代码的效率和质量。 5.总结归纳:在完成一定数量的算法题刷题后,可以对做题有所总结和归纳。思考算法题的分类和解题的技巧,这有助于加深理解并提高解题效率。 三、学习资源 1. LeetCode官方网站:www.leetcode.com 2. 《Python Algorithm Interview》 3. 《算法图解》 4. 数字图书馆:https://www.gitbook.com/book/jalan/leetcode-python/details 5. Github仓库:https://github.com/yuzhoujr/leetcode-python 总结一下,LeetCode题目是提高自己的算法和编程能力的好方法,Python语言无疑是实现目标的好选择;同时,在刷题过程中,理清题目并充分思考,多测试,总结归纳同样重要。希望以上的介绍有助于您更好地学习和刷题

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值