leetcode刷题(9.24总结)

1、相交链表

题目描述:https://leetcode.cn/problems/intersection-of-two-linked-lists/

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        A, B = headA, headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

2、Excel表列名称

题目描述:https://leetcode.cn/problems/excel-sheet-column-title/

class Solution:
    def convertToTitle(self, n: int) -> str:
        t = n
        s = ''
        while t > 0:                # 每次循环 是 每次取模得到数字 的过程
            t -= 1                  # 把 从1开始满27进位 变回 从0开始满26进位
            a, b = t//26, t%26      # 这里b的取值范围是0-25
            s = s + chr(b+65)       # A的ASCII码是65,b+65表示 0-25 和 A-Z 有了一一对应
            t = a
        return s[::-1]              # 最后将 优先获得的低位数字 反转到最后


3、多数元素

题目描述:https://leetcode.cn/problems/majority-element/

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        ans = -1
        cnt = 0
        for num in nums:
            if not cnt:
                ans = num
                cnt = 1
            else:
                if num == ans:
                    cnt += 1
                else:
                    cnt -= 1
        return ans

4、Excel表列序号

题目描述:https://leetcode.cn/problems/excel-sheet-column-number/

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        res = 0
        for c in columnTitle:
            cur = ord(c) - ord('A') + 1
            res = res * 26 + cur
        return res

5、颠倒的二进制位

题目描述:https://leetcode.cn/problems/reverse-bits/


class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for i in range(32):
            res = (res << 1) + (n & 1)
            n >>= 1
        return res

6、位1的个数

题目描述:https://leetcode.cn/problems/number-of-1-bits/

class Solution:
    def hammingWeight(self, n: int) -> int:
        n = bin(n)
        sc = str(n)[2:]
        frequency = collections.Counter(sc)
        return frequency['1']

7、快乐数

题目描述:https://leetcode.cn/problems/happy-number/

class Solution:
    def isHappy(self, n: int) -> bool:
        pre = set([n])
        
        def check(num):
            lst = [int(va)**2 for va in str(num)]
            return sum(lst)
        
        while n!=1:
            n = check(n)
            if n in pre:
                return False
            pre.add(n)
            
        return True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值