leetcode刷題記錄461-470 python版

前言

繼續leetcode刷題生涯
這裏記錄的都是筆者覺得有點意思的做法
參考了好幾位大佬的題解,尤其是powcai大佬和labuladong大佬,感謝各位大佬

461. 漢明距離

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return bin(x ^ y).count("1")

462. 最少移動次數使數組元素相等 II

class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        mid = sorted(nums)[len(nums)//2]
        return sum(abs(num - mid) for num in nums)

463. 島嶼的周長

# 一行
class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        import itertools
        return sum(sum(map(lambda x, y: x!=y, row + [0], [0] + row)) for row in itertools.chain(grid, map(list, zip(*grid))))
# 直接遍歷
class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        res=0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]==1:
                    res+=4
                    if i-1>=0 and grid[i-1][j]==1:
                        res-=2
                    if j-1>=0 and grid[i][j-1]==1:
                        res-=2
        return res

464. 我能贏嗎

class Solution:
    def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
        if maxChoosableInteger >= desiredTotal: return True
        sums = (1+maxChoosableInteger)*maxChoosableInteger // 2
        if sums < desiredTotal: return False
        if sums == desiredTotal: return maxChoosableInteger&1 == 1
        dic = {}
        def isWin(nums, tmp):
            if nums[-1] >= tmp: return True
            seenums = tuple(nums)
            if seenums in dic:
                return dic[seenums]
            for i,num in enumerate(nums):
                if not isWin(nums[:i]+nums[i+1:], tmp-num):
                    dic[seenums] = True
                    return True
            dic[seenums] = False
            return False
        return isWin(list(range(1, maxChoosableInteger+1)), desiredTotal)

466. 統計重複個數

class Solution:
    def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
        dp=[]
        for i in range(len(s2)):
            start=i
            end=0
            for j in range(len(s1)):
                if s1[j] == s2[start]:
                    start+=1
                    if start==len(s2):
                        start=0
                        end+=1
            dp.append((start,end))
        res=0
        next=0
        for _ in range(n1):
            res+=dp[next][1]
            next=dp[next][0]
        return res//n2

467. 環繞字符串中唯一的子字符串

class Solution:
    def findSubstringInWraproundString(self, p: str) -> int:
        if not p: return 0
        hashmap=[0]*26
        hashmap[ord(p[0])-ord("a")]=1
        prelen=1
        for i in range(1,len(p)):
            gap=ord(p[i])-ord(p[i-1])
            if gap==1 or gap==-25:
                prelen+=1
            else:
                prelen=1
            hashmap[ord(p[i])-ord("a")]=max(hashmap[ord(p[i])-ord("a")],prelen)
        return sum(hashmap)

468. 驗證IP地址

class Solution:
    def validIPAddress(self, IP: str) -> str:
        def isIPv4(s):
            try:
                return str(int(s)) == s and 0 <= int(s) <= 255
            except:
                return False
        def isIPv6(s):
            if len(s) > 4: return False
            try:
                return int(s, 16) >= 0 and s[0] != '-'
            except:
                return False
        if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
            return "IPv4"
        if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
            return "IPv6"
        return "Neither"

470. 用 Rand7() 實現 Rand10()

class Solution:
    def rand10(self):
        ans = 41
        while ans >= 40:
            ans = (rand7()-1)*7+rand7()-1
        return ans%10+1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章