Leetcode easy - python 3

本文介绍了Python在解LeetCode简单题目中的应用,包括字符串操作、集合运用、数组处理和位操作等。重点讲解了771. Jewels and Stones、709. To Lower Case、929. Unique Email Addresses等题目的解决方案,通过实例展示如何利用Python简洁高效地解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

771. Jewels and Stones

count(str) 函数:返回字符串str中某个字符的个数

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        n = 0
        for j in J:
            n += S.count(j)
        return n

709. To Lower Case

str.lower() 将str中每个字符都变成小写
str.upper() – 全部大写
str.capitalize() – 把第一个字母转化为大写字母,其余小写
str.title() – 把每个单词的第一个字母转化为大写,其余小写

class Solution:
    def toLowerCase(self, str: str) -> str:
        return str.lower()

929. Unique Email Addresses

在List里面的遍历每个项 直接for循环就可!
index(’+’) – 定位到该字符的位置
‘.’ 可忽略 相当于处理直接用替换’'就可!

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        seen = set()
        for email in emails:
            local, domain = email.split('@')
            if '+' in local:
                local = local[0:local.index('+')]
            seen.add(local.replace('.','') + '@' + domain)
        return len(seen)

804. Unique Morse Code Words

set: 是一个无须且不重复的元素集合
· 如果元素已经存在set里面 则set.add不会添加到set中
返回set中元素的个数:len(set)

我的代码:

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        code = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
        seens = set()
        # form the code string
        for word in words:
            word_code = ""
            for alpha in word:
                alpha_index = alphabet.index(alpha)
                word_code += code[alpha_index]
            #if word_code not exists in seens:
            seens.add(word_code)
        return len(seens)
            
        

标准答案参考

用了ord函数
省去了像我一样二次遍历定位的麻烦

使用join函数 连接生成新的字符串

python代码可以很简洁:

        seen = {"".join(MORSE[ord(c) - ord('a')] for c in word)
                for word in words}

595. Big Countries

omg居然是MySQL的题 过于简单了这道题

# Write your MySQL query statement below
select name, population, area 
from World
where area > 3000000 or population > 25000000;

961. N-Repeated Element in Size 2N Array

我的代码:

class Solution:
    def repeatedNTimes(self, A: List[int]) -> int:
        N = int(len(A)/2)
        for a in A:
            count = A.count(a)
            if count == N:
                return a
                break

标准答案:

Let’s count the number of elements. We can use a HashMap or an array - here, we use a HashMap.
After, the element with a count larger than 1 must be the answer.

关于collections之Counter

因为条件都是确定的 其实并不用算出N的值
只要>1的 就是啦

        count = collections.Counter(A)
        for k in count:  # k:N
            if count[k] > 1:
                return k

977. Squares of a Sorted Array

关于sort和sorted 一个参考

sorted()不会改变原来的list,而是会返回一个新的已经排序好的list

list.sort()方法仅仅被list所定义,sorted()可用于任何一个可迭代对象

class Solution:
    def sortedSquares(self, A: List[int]) -> List[int]:
        op = []
        for a in A:
            op.extend([a*a])
        # print(op)
        return sorted(op)

标准答案:

	return sorted(x*x for x in A)

(尝试简洁代码ing)

461. Hamming Distance

In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.

两个int做交集 不同取1 → bin(x ^ y)

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        res = bin(x ^ y)
        count = 0
        for i in res:
            if i == '1':
                count += 1
        return count
        # standard solution:
        # list可以用count直接计数
        # return list(bin(x ^ y)).count('1')     

136. Single Number

Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

上面这个要求需要满足

        # run time error
        for i in nums:
            if nums.count(i) == 1:
                return i

for循环里面一个一个判断会超时

方法1:
        # Approach 1
        NoduplicateList = []
        for i in nums:
            if i not in NoduplicateList:
                NoduplicateList.append(i)
            else:
                NoduplicateList.remove(i)
        return NoduplicateList.pop()
方法2:哈希表
        hash_table = {}
        for i in nums:
            try:
                hash_table.pop(i) 
                # 和删除list里面值的思想一样
            except:
                hash_table[i] = 1
        return hash_table.popitem()[0] 
        # 只剩一个值

pop(key[,default]):删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

popitem():随机返回并删除字典中的一对键和值。

方法3:这个方法绝了!!!太绝了8

公式:2∗(a+b+c)−(a+a+b+b+c)=c

set()函数 创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

	return 2 * sum(set(nums)) - sum(nums)
方法4:Bit Manipulation

If we take XOR of zero and some bit, it will return that bit
a⊕0 = a

If we take XOR of two same bits, it will return 0
a⊕a = 0

a⊕b⊕a=(a⊕a)⊕b=0⊕b=b

So we can XOR all bits together to find the unique number.

        a = 0
        for i in nums:
            a ^= i
        return a

这个空间复杂度O(1) 时间复杂度O(n)

PS 这个办法也很绝!!!

283. Move Zeroes

这道题的关键在于 remove删着删着 List是会变化的 所以用for循环len(nums)会显示out of range 换成while函数可以解决这个问题 ^^

还有一个点就是:例如第一个就是0,删掉了,那么index应该还是0,而不是+1。反正只要是删除了0,那么index就应该还在原来的position就对啦!

代码如下:

        count = 0
        i = 0
        while i < len(nums):
            if nums[i] == 0:
                nums.remove(nums[i])
                count += 1
            else:
                i += 1
        for k in range(0, count):
            nums.append(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值