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三倍的时间,我也不知道怎么回事。

最新文章

  1. 【BZOJ-4380】Myjnie 区间DP
  2. 11.14 T2 小x的旅行(小x的旅行)
  3. 【菜鸟玩Linux开发】在C++里操作MySQL
  4. Unsafe的应用
  5. ruiy_ocfs2
  6. 使用POI 导入excel
  7. ASP.NET Core WebApi AspNetCoreRateLimit 限流中间件学习
  8. 甘特图 (Gantt )的优缺点
  9. [转载]C++之路起航——标准模板库(deque)
  10. php 建站 多域名配置 自定义重定向
  11. How to set up github to work with Visual Studio 2013
  12. 去中心化存储的QoS是什么?
  13. mongoDB 32位 安装包地址
  14. Google Android API官网封杀了,没法查android技术资料的3种解决方式
  15. Python之模块(二)
  16. unittest框架(三)unittest+yaml数据驱动
  17. SYN 洪泛攻击
  18. web.xml中配置classpath:和classpath*:的区别和意思
  19. 【转】Android开发笔记——圆角和边框们
  20. Jenkins 配置邮箱 530Authentication required ,535 uthentication failed 的解决方法

热门文章

  1. Mac开发环境配置 就喜欢折腾
  2. pandas(一)操作Series和DataFrame的基本功能
  3. 深入理解MVC架构
  4. EXCEL 从网页复制的内容 单/多选框 在EXCEL删不掉 及 2007添加开发工具选项卡
  5. JavaScript 的简单学习2
  6. iOS 几种常用的 crash log 崩溃信息调试方法
  7. OC自动释放池autoreleasepool介绍
  8. 无线路由:关于WDS,Repeater等模式的说明
  9. require.js和sea.js的区别
  10. Spring-data-jpa常用方法