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
相关推荐
码农小韩39 分钟前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法
!chen43 分钟前
Error: error:0308010C:digital envelope routines::unsupporte
python
小北方城市网1 小时前
分布式锁实战指南:从选型到落地,避开 90% 的坑
java·数据库·redis·分布式·python·缓存
wen__xvn1 小时前
第 34 场 蓝桥·算法入门赛·百校联赛
算法
ASD125478acx1 小时前
超声心动图心脏自动检测YOLO11-NetBifPN算法实现与优化
算法
xiaolyuh1231 小时前
【XXL-JOB】 GLUE模式 底层实现原理
java·开发语言·前端·python·xxl-job
likuolei1 小时前
Spring AI框架完整指南
人工智能·python·spring
二哈喇子!2 小时前
PyTorch生态与昇腾平台适配:环境搭建与详细安装指南
人工智能·pytorch·python
Learner2 小时前
Python数据类型(三):列表和元组
开发语言·python
世界唯一最大变量2 小时前
用自创的算法快速解决拉姆奇数
python