当前位置:网站首页>【LeetCode】217. 存在重复元素
【LeetCode】217. 存在重复元素
2022-07-29 14:31:00 【酥酥~】
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
示例 1:
输入:nums = [1,2,3,1]
输出:true
示例 2:
输入:nums = [1,2,3,4]
输出:false
示例 3:
输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
提示:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
题解:
思路1:将数组排序后,相邻元素若重复则返回true,否则返回false
##python
class Solution(object):
def containsDuplicate(self, nums):
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
//C++
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(),nums.end());
for (int i=0;i<n-1;i++)
{
if(nums[i] == nums[i+1])
return true;
}
return false;
}
};
思路2:利用哈希的唯一性
//C++
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> mynums;
for(auto it:nums)
{
if(mynums.find(it) != mynums.end())
return true;
mynums.insert(it);
}
return false;
}
};
边栏推荐
猜你喜欢

嵌入式开发经验分享,把学习当作一种兴趣

面试官:大量请求 Redis 不存在的数据,从而影响数据库,该如何解决?

The raised platform system based on JSP&Servlet implementation

图斑自上而下,自左而右顺序编码,按照权属单位代码分组,每组从1开始编码

【Postman】Download and installation (novice graphic tutorial)

基于SSM实现在线聊天系统

arcgis中编码方式改变引起的shp文件乱码、字符截断问题处理

C51 存储类型与存储模式

国产手机将用户变成它们的广告肉鸡,难怪消费者都买iPhone了

部门例会上做测试分享,不知道分享什么内容?
随机推荐
工业设备数字孪生技术,解决方案系统平台案例
国产手机将用户变成它们的广告肉鸡,难怪消费者都买iPhone了
从一道面试题说起:GET 请求能传图片吗?
Zhaoqi Technology creates a platform for overseas high-level talent introduction, corporate project docking, and event roadshows
Realization of Online Chat System Based on SSM
The reason for Apple's official price reduction has been found, and it is also facing declining sales and even inventory problems
三 RedisTemplate 序列化机制配置实战
没遇到过这三个问题都不好意思说用过Redis
Couldn‘t create temporary file /tmp/apt.conf.uko4Kd for passing config to apt-key
C语言 5:bool类型,关系表达式,逻辑表达式,分支语句,函数调用机制,break,continue,goto,return/exit跳转语句
数字孪生万物可视 |联接现实世界与数字空间
rk3399驱动添加电池adc开机检测功能
【C语言】AI三子棋的成长之路
无线传感器网络定位综述
这个 MySQL bug,99% 的人会踩坑!
双非渣渣的上岸之路!备战60天,三战滴滴侥幸收获Offer
文本处理之xml
基于C语言实现的LL(1)分析
EA&UML日拱一卒-活动图::Variable Actions(续)
Bika LIMS 开源LIMS集—— SENAITE的使用(用户、角色、部门)