代码随想录算法训练营第六天|242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和

349. 两个数组的交集

题目链接:349. 两个数组的交集

思路:

哈希表的思想,遍历数组2寻找同样在数组1中的元素,将找到的元素放入数组3,但同时要考虑数组3中已有的元素不再放入,来避免重复。

代码:
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums3=[]
        for x in nums2:
            if x in nums1 and x not in nums3:
                nums3.append(x)
        return nums3
反思:
  1. 如果得到数组3中含有重复元素,如何去重
s = [1,3,2,6,3,1,1,4,4,5]
m = list(set(s))
print(m)

输出结果:

[1, 2, 3, 4, 5, 6]

此时去重后改变了序列的顺序,若要保持原来的顺序,需要依照元素索引进行排序

s = [1,3,2,6,3,1,1,4,4,5]
m = list(set(s))
m.sort(key=s.index)
print(m)

输出结果:

[1, 3, 2, 6, 4, 5]
  1. set()用法
    set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等
>>>x = set('runoob')
>>> y = set('google')
>>> x, y
 # 重复的被删除
(set(['b', 'r','u','o','n']),set(['e', 'o', 'g', 'l']))  
>>> x & y       # 交集
set(['o'])
>>> x | y      # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
>>> x - y      # 差集
set(['r', 'b', 'u', 'n'])
>>>

202. 快乐数

题目链接:202. 快乐数

思路:

将整数转换为字符串后取出各位上的数字,再将各位置上的数字转换为整型,平方求和。当和已经出现过时,输出False,当和为1时,输出True

class Solution:
    def isHappy(self, n: int) -> bool:
        n1=n
        value=[n1]
        while(n1!=1):
            m=str(n1)
            summ=0
            for x in m:
                summ+=int(x)**2
            if summ in value:
                return False
            value.append(summ)
            n1=summ
        return True
反思:
  1. bool类型只有‘True’&‘False’,‘true’&‘false’和‘TRUE’&‘FALSE’不是
  2. 整型转换为字符串&字符串转换为整数

str() 将整型转换为字符串

a=123
b=str(a)

输出结果为:

'123'

int() 将字符串转换为整数

b='123'
c=int(b)

输出结果为:

123
  1. 字符串可以遍历,可以计算长度,但不可以索引
    在这里插入图片描述

  2. 一开始要把n赋值给n1,不要直接对n进行处理

官方:

看了官方题解,官方在提取各位数的时候用了divmod函数,值得借鉴

class Solution:
    def isHappy(self, n: int) -> bool:
        def get_next(n):
            total_sum = 0
            while n > 0:
                n, digit = divmod(n, 10)
                total_sum += digit ** 2
            return total_sum

        seen = set()
        while n != 1 and n not in seen:
            seen.add(n)
            n = get_next(n)

        return n == 1
  • divmod()
    • 如果x和y是整数,则divmod()的返回值与(a // b,x%y)相同.
    • 如果x或y的值为浮点型,则结果为(q,x%y). 在此,q是商的整个部分.
    • divmod(8, 3) = (2, 2)
    • divmod(8.0, 3) = (2.0, 2.0)

有效的字母异位词

题目链接:有效的字母异位词

思路:

建立空字典value,首先统计s中字母和对应的数量,然后再遍历t,看里面字母是否都在value中,在的话就值减一,不在就返回False。最后再检查value的值是否都为零,不是的话就返回False,否则True。

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        value={}
        for x in s:
            if x not in value.keys():
                value[x]=1
            else:
                value[x]+=1
        for x in t:
            if x not in value.keys():
                return False
            else:
                value[x]-=1
        for y in value.values():
            if y:
                return False
        return True
代码随想录:

这边是将英文26个字母变为一个哈希表。有一个优点,比我考虑的少了一个if的判断(我需要判断这个是否在s中),而这边哪怕不在输出的是负数,也方便最后判断是否为零。

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        record = [0] * 26
        for i in range(len(s)):
            #并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
            record[ord(s[i]) - ord("a")] += 1
        print(record)
        for i in range(len(t)):
            record[ord(t[i]) - ord("a")] -= 1
        for i in range(26):
            if record[i] != 0:
                #record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
                return False
        return True

1.两数之和

题目链接:1.两数之和

思路:

遍历数组,取到nums[i],判断target-nums[i]是否在数组剩下部分中,在的话,就取第一个下标为i;然后再在剩下的数组中遍历求第二个下标j

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n=0
        index=[]
        ss=nums
        for i in range(len(ss)):
            a=target-ss[i]
            s=ss[i+1:]
            if a in s:
                index.append(i)
                break

        for j in range(index[0]+1,len(ss)):
            if ss[j]==a:
                index.append(j)
        return index
代码随想录:
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = dict()

        for index, value in enumerate(nums):
            if target - value in records:
                return [records[target- value], index]
            records[value] = index
        return []

并不需要循环两次。创建一个字典,当值在字典中时返回当前索引下标和搜索到值的下标

反思:

1.enumerate()用法

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

seasons = [‘Spring’, ‘Summer’, ‘Fall’, ‘Winter’]

list(enumerate(seasons))
[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’)]

tuple(enumerate(seasons, start=1))
((1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’))

for遍历情况:

seq = [‘one’, ‘two’, ‘three’]

for temp in enumerate(seq):
print(temp)

(0, 'one')
(1, 'two')
(2, 'three')

for i, element in enumerate(seq):
print (i, element)

0 one
1 two
2 three

今日总结

这个day6写了好几天,每天写一点,感觉收获了不少细碎的知识点
准备学学C++

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值