题目描述:

解题思路:
对list进行去重,去重之后,list的长度如果不变,证明原list中没有重复元素,返回False;去重之后,list的长度如果改变(减少),证明原list中存在重复元素,返回True。
列表如何去重是关键:
1.先将list强转为set类型,利用set的特性,自动去重。然后再将set转回list.
2.将list的元素当作字典的key创建字典,因为字典的key要求不能重复,所以会自动去重。
3.创建一个空list,遍历一遍原来的list,不在空list中的元素,放入。这样也可以去重。
list去重,参考链接:https://blog.csdn.net/zh6526157/article/details/122516733
代码:
方法一:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
old_length = len(nums)
new_list = list(set(nums))
new_length = len(new_list)
if new_length == old_length:
return False
else:
return True

方法二(超时):
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
temp = []
for i in nums:
if i not in temp:
temp.append(i)
if len(temp) == len(nums):
return False
else:
return True

方法三:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
new_list = list(dict.fromkeys(nums))
if len(nums) == len(new_list):
return False
else:
return True

本文介绍了三种Python中判断列表是否包含重复元素的方法,包括利用set的去重特性、字典的键唯一性以及创建新列表排除重复项。通过比较去重后的列表长度与原列表长度来确定是否存在重复。这些方法对于理解和操作Python列表非常实用。
736

被折叠的 条评论
为什么被折叠?



