力扣(LeetCode)简单算法题 --- Python3

目录

1、回文数

13、罗马数字转整数

14、最长的公共前缀

20、有效的括号

26、删除有序数组中的重复项

27、移除元素

35、搜索插入位置

58、最后一个单词的长度

66、加一

67、二进制求和

69、x的平方根

70、爬楼梯

118、杨辉三角

119、杨辉三角Ⅱ  返回「杨辉三角」的第 rowIndex 行

121、买卖股票的最好时机

125、验证回文串

136、只出现一次的数字

168、Excel表列名称

169、多数元素

171、Excel表列序号

190、颠倒二进制位

191、位1的个数

202、快乐数

205、同构字符串

217、存在重复元素

219、存在重复元素Ⅱ

228、汇总区间

231、2的幂

242、有效的字母异位词

258、个位相加

263、丑数

268、丢失的数字

283、移动零

290、单词规律

292、Nim

303、区域和检索 - 数组不可变

326、3的幂

338、比特位计数

342、4的幂

344、反转字符串

345、反转字符串中的元音字母

349、两个数组的交集

350、两个数组的交集 II


1、回文数

def isPalindrome(x):
    if x < 0:
        return False
    else:
        string = str(x)
        len_x = len(string)
        for i in range(len_x):
            if string[i] == string[len_x - i - 1]:
                continue
            else:
                return False
    return True
print(isPalindrome(1010021))

13、罗马数字转整数

def romanToInt(s):
    num = 0
    s = s.replace("IV", "A")
    s = s.replace("IX", "B")
    s = s.replace("XL", "Y")
    s = s.replace("XC", "Z")
    s = s.replace("CD", "E")
    s = s.replace("CM", "F")
    print(s)
    for j in s:
        if j == 'I':
            num += 1
        elif j == 'V':
            num += 5
        elif j == 'X':
            num += 10
        elif j == 'L':
            num += 50
        elif j == 'C':
            num += 100
        elif j == 'D':
            num += 500
        elif j == 'M':
            num += 1000
        elif j == 'A':
            num += 4
        elif j == 'B':
            num += 9
        elif j == 'Y':
            num += 40
        elif j == 'Z':
            num += 90
        elif j == 'E':
            num += 400
        elif j == 'F':
            num += 900
    return num

print(romanToInt('MCMXCIV'))

14、最长的公共前缀

def longestCommonPrefix(strs):
    strs.sort()
    first_word = strs[0]
    last_word = strs[-1]
    res_prefix = ''
    for tup in zip(first_word, last_word):
        if len(set(tup)) == 1:          # 无序去重排列
            res_prefix += tup[0]
        else:
            break
    return res_prefix

20、有效的括号

def isValid(s):
    if len(s) % 2 == 1:
        return False

    pairs = {
        ")": "(",
        "]": "[",
        "}": "{",
    }
    lists = []
    for i in s:
        if i in pairs:
            if not lists or lists[-1] != pairs[i]:      # 如果lists里面没有元素或者lists[-1] != pairs[i]时,返回False
                return False
            lists.pop()
        else:
            lists.append(i)
    return not lists                # 如果lists里面没有元素时,返回True
print(isValid('{[}'))

26、删除有序数组中的重复项

def removeDuplicates(nums):
    for i in range(len(nums)):
        new = nums[i:]
        for j in new[1:]:
            if nums[i] == j:
                nums.remove(j)
    length = len(nums)
    return length
print(removeDuplicates([1,1,2]))

27、移除元素

def removeElement(nums, val):
    length = len(nums)
    for i in range(length - 1, -1, -1):       # 必须倒序删除。顺序删除时,列表中索引上的值会随删除的同时改变
        if nums[i] == val:
            nums.remove(nums[i])
    return len(nums)
print(removeElement(nums=[0,1,2,2,3,0,4,2], val=2))

35、搜索插入位置

def searchInsert(nums, target):
    index = 0
    for i in range(len(nums)-1, -1, -1):
        print('i = ', i)
        if target in nums:
            if target == nums[i]:
                index = i
        else:
            if target > nums[i]:
                print('nums[i] = ', nums[i])
                index = i + 1
                break
    return index
print(searchInsert(nums = [1, 3, 5, 6], target = 2))

58、最后一个单词的长度

def lengthOfLastWord(s):
    length = 0
    new_s = s.split(" ")
    for i in range(len(new_s) - 1, -1, -1):
        if len(new_s[i]) >= 1:
            length = len(new_s[i])
            break
    return length
print(lengthOfLastWord("   fly me   to   the moon  "))

66、加一

def plusOne(digits):
    for i in range(len(digits) - 1, -1, -1):
        if digits[i] < 9:
            digits[i] += 1
            break
        elif digits[i] == 9:
            digits[i] = 0
            if i == 0:
                digits[0] = 1
                digits.append(0)
    return digits

print(plusOne([8, 9]))

67、二进制求和

def addBinary(a, b):
    x, y = int(a, 2), int(b, 2)
    while y:
        answer = x ^ y
        carry = (x & y) << 1
        x, y = answer, carry
    return bin(x)[2:]
    # return bin(int(a,2)+int(b,2))[2:]

print(addBinary("11", "1"))

69、x的平方根

def mySqrt(x):
    if x < 1:
        return x
    elif x == 1:
        return x
    elif x < 4:
        return 1
    elif x >= 4:
        for i in range(1, x):
            low = i * i
            hight = (i + 1) * (i + 1)
            if low <= x < hight:
                return i
print(mySqrt(8))

70、爬楼梯

def climbStairs(n):
    n1 = 1
    n2 = 2
    if n <3:
        return n
    elif n >= 3:
        for i in range(3, n + 1):       # 斐波那契数
            n2 = n1 + n2
            n1 = n2 - n1
    return n2
print(climbStairs(100))

118、杨辉三角

def generate(numRows):
    ret = []
    for i in range(numRows):
        row = []
        for j in range(i + 1):
            if j == 0 or j == i:
                row.append(1)
            else:
                row.append(ret[i - 1][j] + ret[i - 1][j - 1])
        ret.append(row)
    return ret

print(generate(4))

119、杨辉三角Ⅱ  返回「杨辉三角」的第 rowIndex 行

def getRow(rowIndex):
    ret = []
    for i in range(rowIndex + 1):
        row = []
        for j in range(i + 1):
            if j == 0 or j == i:
                row.append(1)
            else:
                row.append(ret[i - 1][j] + ret[i - 1][j - 1])
        ret.append(row)
    return ret[-1]
print(getRow(4))

121、买卖股票的最好时机

# 此方法会超时
# def maxProfit(prices):
#     ans = 0
#     for i in range(len(prices)):
#         for j in range(i + 1, len(prices)):
#             ans = max(ans, prices[j] - prices[i])
#     return ans
# print(maxProfit([2, 4, 1]))

# def maxProfit(prices):
#     inf = int(1e9)
#     minprice = inf
#     maxprofit = 0
#     for price in prices:
#         maxprofit = max(price - minprice, maxprofit)
#         minprice = min(price, minprice)
#     return maxprofit
# print(maxProfit([7, 1, 5, 3, 6, 4]))

125、验证回文串

# s = "A man, a plan, a canal: Panama"
def isPalindrome(s):
    s = s.lower()
    temp = []
    for i in range(len(s)):
        if ord(s[i]) in range(97, 123):
            temp.append(s[i])
        elif ord(s[i]) in range(48, 58):
            temp.append(s[i])
    r_s = temp[::-1]
    if r_s == temp:
        return True
    else:
        return False
print(isPalindrome("0p"))

136、只出现一次的数字

from functools import reduce
def singleNumber(nums):
    return reduce(lambda x, y: x ^ y, nums)

print(singleNumber([2, 3, 2, 3, 1]))
"""
reduce(函数,序列[,初始])->值
将两个参数的函数累积应用于序列的项,
以便将序列减少为单个值。
例如,reduce(lambda x,y:x+y,[1,2,3,4,5])计算((((1+2)+3)+4)+5). 如果有首字母,则放在项目之前当序列为空。

"""

168、Excel表列名称

def convertToTitle(columnNumber):
    ans = []
    while columnNumber > 0:
        columnNumber -= 1
        ans.append(chr(columnNumber % 26 + ord("A")))
        columnNumber //= 26
    return "".join(ans[::-1])
print(convertToTitle(11152))

169、多数元素

def majorityElement(nums):
    nums.sort()
    return nums[len(nums)//2]
print(majorityElement([3, 2, 3]))

171、Excel表列序号

def titleToNumber(columnTitle):
    number = 0
    multiple = 1
    for i in range(len(columnTitle) - 1, -1, -1):
        num = ord(columnTitle[i]) - ord("A") + 1
        number = number + num * multiple
        multiple *= 26
    return number
print(titleToNumber('AB'))

190、颠倒二进制位

def reverseBits(n):
    s = str(bin(n))[2:]
    ss = s.zfill(32)[::-1]
    return int(ss, 2)
print(reverseBits(11111111111111111111111111111101))

n = 11111111111111111111111111111101
print("0b"+("0"*32+bin(n)[2:]))
print("0b"+("0"*32+bin(n)[2:])[-32:])
print("0b"+("0"*32+bin(n)[2:])[-32:][::-1])
print(int("0b"+("0"*32+bin(n)[2:])[-32:][::-1], base=2))

191、位1的个数

def hammingWeight(self, n: int) -> int:
    ret = sum(1 for i in range(32) if n & (1 << i))
    return ret

202、快乐数

def isHappy(n):
    def get_next(n):
        sum = 0
        while n > 0:
            n, digit = divmod(n, 10)
            sum += digit ** 2
        return sum
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        print('seen = ', seen)
        n = get_next(n)
    return n == 1
print(isHappy(1999999999))


# python divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
# divmod(7, 2)
# (3, 1)

205、同构字符串

def isIsomorphic(s, t):
    return len(set(s)) == len(set(t)) and len(set(s)) == len(set(zip(s, t)))

print(isIsomorphic('ggegg', 'wwadd'))

217、存在重复元素

def containsDuplicate(nums):
    return len(set(nums)) != len(nums)
print(containsDuplicate([1, 2, 3, 5]))

219、存在重复元素Ⅱ

def containsNearbyDuplicate(nums, k):
    pos = {}
    for i, num in enumerate(nums):
        # print('i =', i, end=' ')
        # print('num =', num)
        # print()
        if num in pos and i - pos[num] <= k:
            return True
        pos[num] = i
        # print('pos[num] =', pos[num])
        # print(pos)
        # print()
    return False

print(containsNearbyDuplicate([1, 2, 3, 1], 3))


# 下面这个会超时
# nums = [1, 2, 3, 1]
# k = 3
# for i in range(len(nums)):
#     print('i = ', nums[i])
#     for j in range(i-1, -1, -1):
#         print('j =', nums[j])
#         if nums[i] == nums[j] and abs(i - j) <= k:
#             print('YES')
#             break
#         else:
#             continue


# Python enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,
# 同时列出数据和数据下标,一般用在 for 循环当中。
# >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
# >>> list(enumerate(seasons))
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

228、汇总区间

def summaryRanges(nums):
    n = len(nums)
    res = []
    i, j = 0, 0
    while j < n:
        if j < n - 1 and nums[j + 1] == nums[j] + 1:
            j += 1
        else:
            res.append((nums[i], nums[j]))
            i = j + 1
            j = j + 1

    def p(x):
        a, b = x
        if a == b:
            return str(a)
        else:
            return str(a) + '->' + str(b)

    return list(map(p, res))
print(summaryRanges([0,1,2,4,5,7]))


# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
# >>> def square(x) :            # 计算平方数
# ...     return x ** 2
# ...
# >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
# [1, 4, 9, 16, 25]

231、2的幂

def isPowerOfTwo(n):
    num = 0
    i = 1
    if n == 1:
        return True
    elif n <= 1:
        return False
    elif n > 1:
        while i >= 1:
            num = 2 ** i
            i += 1
            if num == n:
                return True
            if num > n:
                return False
print(isPowerOfTwo(1024))

242、有效的字母异位词

def isAnagram(s, t):
    if len(s) == len(t):
        for i in s:
            if i in t and t.count(i) == s.count(i):
                continue
            else:
                return False
        return True
    else:
        return False

print(isAnagram("rat", "car"))

258、个位相加

def addDigits(num):
    while num > 9:
        a = num % 10
        num -= a
        num = num // 10
        num += a
    return num
print(addDigits(338))

263、丑数

def isUgly(n):
    if n <= 0:
        return False

    factors = [2, 3, 5]
    for factor in factors:
        while n % factor == 0:
            n //= factor

    return n == 1
print(isUgly(34))

268、丢失的数字

def missingNumber(nums):
    length = len(nums)
    num = length * (length + 1) / 2
    for i in nums:
        num -= i
    return int(num)

print(missingNumber([3, 0, 1]))

283、移动零

def moveZeroes(nums):
    """
    Do not return anything, modify nums in-place instead.
    """
    for i in nums:
        if i == 0:
            nums.remove(i)
            nums.append(0)
    # print(nums)
print(moveZeroes([0, 1, 0, 3, 12]))

290、单词规律

def wordPattern(pattern, s) -> bool:
    s = s.split(' ')
    if len(pattern) == len(s):
        if len(pattern) == 1:
            return True
        elif len(pattern) > 1:
            for i in range(len(pattern) - 1):
                for j in range(i + 1, len(pattern)):
                    if pattern[i] == pattern[j] and s[j] == s[i]:
                        continue
                    elif pattern[i] == pattern[j] and s[j] != s[i]:
                        return False
                    elif s[j] == s[i] and pattern[i] != pattern[j]:
                        return False
    else:
        return False
    return True
print(wordPattern("e", "eukera"))

292、Nim

def canWinNim(n):
    return n % 4 != 0

# 显而易见的是,如果石头堆中只有一块、两块、或是三块石头,那么在你的回合,你就可以把全部石子拿走,从而在游戏中取胜;
# 如果堆中恰好有四块石头,你就会失败。因为在这种情况下不管你取走多少石头,
# 总会为你的对手留下几块,他可以将剩余的石头全部取完,从而他可以在游戏中打败你。
# 因此,要想获胜,在你的回合中,必须避免石头堆中的石子数为 4 的情况。

303、区域和检索 - 数组不可变

def __init__(self, nums: List[int]):
    self.sums = [0]
    _sums = self.sums

    for num in nums:
        _sums.append(_sums[-1] + num)

def sumRange(self, i: int, j: int) -> int:
    _sums = self.sums
    return _sums[j + 1] - _sums[i]

326、3的幂

def isPowerOfThree(n):
    if n <= 0:
        return False
    for i in range(n):
        if 3 ** i == n:
            return True
        elif 3 ** i > n:
            return False
print(isPowerOfThree(9))

338、比特位计数

def countBits(n):
    res = []
    for i in range(n + 1):
        tem = str(bin(i))
        num = 0
        for j in tem[2:]:
            # print(j)
            if int(j) == 1:
                num += 1
        res.append(num)
    return res
print(countBits(5))

342、4的幂

def isPowerOfFour(n):
    if n <= 0:
        return False
    for i in range(n):
        if 4 ** i == n:
            return True
        elif 4 ** i > n:
            return False
print(isPowerOfFour(16))

344、反转字符串

def reverseString(s):
    """
    Do not return anything, modify s in-place instead.
    """
    s[:] = s[::-1]
print(reverseString(["h", "e", "l", "l", "o"]))

345、反转字符串中的元音字母

def reverseVowels(s):
    s = list(s)
    vowel = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']
    left = 0
    right = len(s) - 1
    while left < right:
        while left < right and s[left] not in vowel:
            left += 1
        while left < right and s[right] not in vowel:
            right -= 1
        if left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1
    return "".join(s)
print(reverseVowels("leetcode"))

349、两个数组的交集

def intersection(nums1, nums2):
    inter = []
    for i in nums1:
        if i in nums2:
            inter.append(i)
    return list(set(inter))
print(intersection([1, 2, 2, 1], [2, 2]))

350、两个数组的交集 II

def intersect(nums1, nums2):
    inter = []
    for i in nums1:
        if i in nums2:
            inter.append(i)
            nums2.remove(i)
    return inter
print(intersect([1, 2, 2, 1], [2]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戲子 鬧京城°ぃ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值