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
相关推荐
数据知道4 分钟前
claw-code 源码详细分析:Bootstrap Graph——启动阶段图式化之后,排障与扩展为什么会变简单?
前端·算法·ai·bootstrap·claude code·claw code
Kel7 分钟前
从Prompt到Response:大模型推理端到端核心链路深度拆解
人工智能·算法·架构
Felven7 分钟前
D. Matryoshkas
算法
17(无规则自律)20 分钟前
DFS连通域统计:岛屿数量问题及其变形
c++·算法·深度优先
ZC跨境爬虫24 分钟前
极验滑动验证码自动化实战(ddddocr免费方案):本地缺口识别与Playwright滑动模拟
前端·爬虫·python·自动化
笨笨饿37 分钟前
34_数据结构_栈
c语言·开发语言·数据结构·人工智能·嵌入式硬件·算法
单片机学习之路1 小时前
【Python】输入print函数
开发语言·前端·python
后藤十八里1 小时前
极验4消消乐验证码逆向笔记
笔记·爬虫·python
im_AMBER1 小时前
Leetcode 152 被围绕的区域 | 岛屿数量
数据结构·算法·leetcode·深度优先·广度优先·图搜索算法
李昊哲小课1 小时前
Python办公自动化教程 - 第1章 openpyxl基础入门 - 第一次用代码操控Excel
开发语言·python·excel·openpyxl