Datawhale刷题LeetCode

Task1:数据结构与算法简介、LeetCode ⼊⻔及攻略

0001.两数之和

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = {}

        for idx,val in enumerate(nums):
            if target-val not in records:
                records[val] = idx
            else:
                return [records[target-val],idx]

1929.数组串联

+ 学到 extend()无返回值,是在原始数组进行的修改

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        nums.extend(nums)
        return nums

0771.宝石与石头

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        nums = 0
        for i in set(jewels):
            count = stones.count(i)
            nums+=count
        return nums

官方题解

+ 我觉得我的方法应该进行简化!

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        jewelsSet = set(jewels)
        return sum(s in jewelsSet for s in stones)

Task 02:数组基础

0066.加一

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        return list(map(int,str(int("".join(map(str,digits)))+1)))

0724.寻找数组的中心下标

2 x [ 左求和 ]  + 中间值 = 数组所有

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        numSum = sum(nums)
        leftSum = 0
        for i in range(len(nums)):
            if numSum-leftSum-nums[i] == leftSum:
                return i
            leftSum+=nums[i]             
        return -1
            

0189.旋转数组

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if k > length:
            k = k % length
        nums_1,nums_2 = nums[length-k:length],nums[:length-k]
        nums[:k],nums[k:] = nums_1,nums_2

0048.旋转图像

0054.螺旋矩阵

0498.对角线遍历

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>