LeetCode OJ:Contains Duplicate(是否包含重复)
2024-08-27 03:55:45
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
判断数组里面是否有重复的,很简单:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int sz = nums.size();
if (sz <= ) return true;
sort(nums.begin(), nums.end());
for (int i = ; i < sz; ++i){
if (nums[i] == nums[i - ])
return false;
}
return true;
}
};
java版本,用HashSet来做的,这样的效率应该比上面的要高上不少,代码如下:
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> s = new HashSet<Integer>();
for(int i = 0; i< nums.length; ++i){
if(!s.contains(nums[i])){
s.add(nums[i]);
}else
return true;
}
return false;
}
}
c++的Hash代码也写一遍试试:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int sz = nums.size();
unordered_set<int> s;
for(int i = 0; i < sz; ++i){
if(s.find(nums[i]) == s.end()){
s.insert(nums[i]);
}else
return true;
}
return false;
}
};
发现实际上比java的runtime还是要慢上不少,大概用了java三倍的时间,我也不知道怎么回事。
最新文章
- 【BZOJ-4380】Myjnie 区间DP
- 11.14 T2 小x的旅行(小x的旅行)
- 【菜鸟玩Linux开发】在C++里操作MySQL
- Unsafe的应用
- ruiy_ocfs2
- 使用POI 导入excel
- ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件学习
- 甘特图 (Gantt )的优缺点
- [转载]C++之路起航——标准模板库(deque)
- php 建站 多域名配置 自定义重定向
- How to set up github to work with Visual Studio 2013
- 去中心化存储的QoS是什么?
- mongoDB 32位 安装包地址
- Google Android API官网封杀了,没法查android技术资料的3种解决方式
- Python之模块(二)
- unittest框架(三)unittest+yaml数据驱动
- SYN 洪泛攻击
- web.xml中配置classpath:和classpath*:的区别和意思
- 【转】Android开发笔记——圆角和边框们
- Jenkins 配置邮箱 530Authentication required ,535 uthentication failed 的解决方法