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: Listint) -> 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
相关推荐
黄忠17 分钟前
大模型之LangGraph技术体系
python·llm
JieE21212 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21212 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
hboot13 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
vivo互联网技术17 小时前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
用户83562907805118 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
Darling噜啦啦18 小时前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户83562907805119 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
用户4978630507321 小时前
(一)小红的数组操作
算法·编程语言