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
相关推荐
淡忘旧梦1 分钟前
词错误率/WER算法讲解
人工智能·笔记·python·深度学习·算法
癫狂的兔子3 分钟前
【Python】【爬虫】爬取虎扑网NBA排行数据
数据库·爬虫·python
Aurora-Borealis.10 分钟前
Day40 早停策略和模型权重的保存
python
好大哥呀12 分钟前
如何在手机上运行Python程序
开发语言·python·智能手机
狐5712 分钟前
2026-01-21-牛客每日一题-静态区间和(前缀和)
笔记·算法
_codemonster13 分钟前
手语识别及翻译项目实战系列(一)环境准备
人工智能·python·计算机视觉
毕设源码-钟学长14 分钟前
【开题答辩全过程】以 基于Python的新闻热点舆情分析系统为例,包含答辩的问题和答案
开发语言·python
2401_8414956414 分钟前
【Python高级编程】单词统计与查找分析工具
数据结构·python·算法·gui·排序·单词统计·查找
XerCis14 分钟前
Python代码检查与格式化工具Ruff
开发语言·python
西红市杰出青年22 分钟前
asyncio.gather 内部原理与运行机制(详解)
网络·python·异步