python实现判断数组中是否存在重复元素

1.问题来源

https://leetcode-cn.com/problems/contains-duplicate/description/

2.代码实现,有以下三种方法:

方法一:通过排序,然后判断相邻的两个元素是否相等

代码:

def judgeDuplicated(array):
    array.sort()
    count=0
    while count<len(array)-1:
        if array[count]==array[count+1]:
            return True
        else:
            count+=1
    return False
if __name__ == '__main__':
    array=[1,4,4,1]
    print(judgeDuplicated(array))

方法二:使用字典

代码:

def judgeRepeated(array):
    nums={}
    for i in array:
        if i  not in nums:
            nums[i]=True
        else:
            return True
    return False

方法三:使用集合set(set和其他方法一样,存储的数据都是无序不重复的数据),我们可以通过判断列表转元组之后的长度是否和原长度相等来实现

代码:
def judgeRepeatedThird(array):
    if len(set(array))==len(array):
        return False
    else:
        return True

猜你喜欢

转载自blog.csdn.net/weixin_42153985/article/details/85716179