leetcode python3 简单题217. Contains Duplicate

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百一十七题

(1)题目
英文:
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

中文:
给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate

(2)解法
① set法
(耗时:56ms,内存:19M)

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        return len(nums) > len(set(nums))

② count,这个需要转成str才能使用,包含了对负数的讨论,但是没有对位数超过1的情况进行讨论哦,如有解法可以评论哦

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        string = ''.join([str(i) for i in nums])
        string1 = string
        string2 = ''
        for index, num in enumerate(string) :
            if num=='-':
                if string.count('-'+string[index+1])>1:
                    return True
                else:
                    string2 = string1.replace('-'+string[index+1], '')
            else:
                if string2.count(num)>1:
                    return True
        return False

注意:
1.''.join([str(i) for i in nums])中join要求对象是list,并且list中的每个元素都要是str的,使用’'来连接这些元素,也可以换成其他的。
2.python中对string进行操作没有list方便,所以最好还是先转化为list再继续。
3.string.strip(‘某个字符或字符串’),只能删掉首尾的哦。
4.string.replace(‘某个字符或字符串’, ‘要替换的字符或字符串’, 替换的次数(可以不写)),并且不能直接改变string,需要另外定义一个变量来装这个改变的string。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值