leetcode217. Contains Duplicate

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]

Output: true

Explanation:

The element 1 occurs at the indices 0 and 3.

Example 2:

Input: nums = [1,2,3,4]

Output: false

Explanation:

All elements are distinct.

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]

Output: true

给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。

解题思路

方法1:利用set一行解决

方法2:先排序,然后判断相邻的两个元素是否相等,如果相等则说明存在重复的元素

代码

class Solution:

def containsDuplicate(self, nums: List[int]) -> bool:

return not len(set(nums))==len(nums)

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

复制代码
    #方法2:先排序,然后判断相邻的两个元素是否相等,如果相等则说明存在重复的元素
    # nums.sort()
    # j = 1
    # while j < len(nums):
    #     if nums[j-1] == nums[j]:
    #         return True
    #     else:
    #         j += 1
    # return False
相关推荐
ZPC821026 分钟前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC821026 分钟前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David29 分钟前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱37 分钟前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone1 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩1 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
QQ4022054961 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再1 小时前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082851 小时前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884751 小时前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask