0117leetcode刷题5道python

169

题目描述:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例:
在这里插入图片描述

解答:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        '''
        因为一定有众数,且该数大于n/2
        则排序后最中间的一定是众数
        '''
        nums.sort()
        return nums[len(nums)//2]

191

题目描述:
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例:
在这里插入图片描述
解答:

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count('1')

1603

题目描述:
请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。
请你实现 ParkingSystem 类:
ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类,三个参数分别对应每种停车位的数目。
bool addCar(int carType) 检查是否有 carType 对应的停车位。 carType 有三种类型:大,中,小,分别用数字 1, 2 和 3 表示。一辆车只能停在 carType 对应尺寸的停车位中。如果没有空车位,请返回 false ,否则将该车停入车位并返回 true 。

示例:
在这里插入图片描述
解答:

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self.big=big
        self.medium=medium
        self.small=small


    def addCar(self, carType: int) -> bool:
        if carType==1 and self.big>0:
            self.big-=1
            return True
        elif carType==2 and self.medium>0:
            self.medium-=1
            return True
        elif carType==3 and self.small>0:
            self.small-=1
            return True
        else:
            return False



# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)

1678

题目描述:
请你设计一个可以解释字符串 command 的 Goal 解析器 。command 由 “G”、"()" 和/或 “(al)” 按某种顺序组成。Goal 解析器会将 “G” 解释为字符串 “G”、"()" 解释为字符串 “o” ,"(al)" 解释为字符串 “al” 。然后,按原顺序将经解释得到的字符串连接成一个字符串。
给你字符串 command ,返回 Goal 解析器 对 command 的解释结果。

示例:
在这里插入图片描述
解答:

class Solution:
    def interpret(self, command: str) -> str:
        return command.replace("()","o").replace("(al)","al")

面试题08.04

题目描述:
幂集。编写一种方法,返回某集合的所有子集。集合中不包含重复的元素。
说明:解集不能包含重复的子集。

示例:
在这里插入图片描述
解答:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res=[[]]
        for num in nums:
            res+=[r+[num] for r in res]
        return res

猜你喜欢

转载自blog.csdn.net/yeqing1997/article/details/112647590