题目:

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.

链接: http://leetcode.com/problems/contains-duplicate/

题解:

求数组中是否有重复元素。第一反应是用HashSet。 还可以用Bitmap来写。二刷要都补充上。

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums == null || nums.length == 0)
return false;
Set<Integer> set = new HashSet<>(); for(int i : nums) {
if(set.contains(i))
return true;
else
set.add(i);
} return false;
}
}

二刷:

也是跟1刷一样,使用一个Set来判断

Java:

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
Set<Integer> set = new HashSet<>();
for (int i : nums) {
if (!set.add(i)) {
return true;
}
}
return false;
}
}

三刷:

直接使用set的话会超时,我们需要给Set设置一个初始值来避免resizing的过程。一般来说loading factor大约是0.75,最大的test case大约是30000个数字,所以我们用40000左右的容量的HashSet应该就足够了,这里我选的41000。

这道题也可以先排序再比较前后两个元素,那样的话是O(nlogn)时间复杂度,但可以做到O(1)空间复杂度。

Java:

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums == null) {
return false;
}
Set<Integer> set = new HashSet<>(41000);
for (int i : nums) {
if (!set.add(i)) {
return true;
}
}
return false;
}
}

Update:

再写却并没有碰到超时的情况。

public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>(nums.length);
for (int num : nums) {
if (!set.add(num)) return true;
}
return false;
}
}

Reference:

https://leetcode.com/discuss/70186/88%25-and-99%25-java-solutions-with-custom-hashing

https://leetcode.com/discuss/59208/20ms-c-use-bitmap

https://leetcode.com/discuss/37219/possible-solutions

https://leetcode.com/discuss/37190/java-o-n-ac-solutions-with-hashset-and-bitset

最新文章

  1. CentOS升级openssl
  2. iOS-提高iOS开发效率的方法和工具
  3. 关于ios苹果系统的中的右键事件,查遍了全网都没有的小技巧。
  4. java语言一维数组,对象数组
  5. 在网页中插入MSN,Skype,QQ的方法
  6. C#类的一些概念
  7. Mac搭建本地svn服务器,并用Cornerstone连接服务器
  8. PHP开发APP接口----单例模式连接数据库
  9. MySQL锁监视器
  10. 【JavaScript】使用面向对象的技术创建高级 Web 应用程序
  11. 【转】oracle PLSQL常用方法汇总
  12. 关于日历控件My97DatePicker 在IE6下出现“无法打开站点,已终止操作”
  13. Vs2010发布Asp.Net网站及挂到IIS服务上
  14. 阿里云ECS每天一件事D2:配置防火墙
  15. 深入Java单例模式
  16. android 5.0新特性学习--视图阴影
  17. 迭代与JDB
  18. Codeforces 803 G. Periodic RMQ Problem
  19. 使用Google ZXing生成和解析二维码
  20. ServletContext详解(转)

热门文章

  1. bzoj 3626 LCA
  2. DQL_数据查询语言
  3. JQ跑马灯
  4. JQuery的过滤选择器
  5. 大型网站用什么技术比较好,JSP,PHP,ASP.NET
  6. Spark机器学习 Day1 机器学习概述
  7. C#快速学习笔记(译)续一
  8. u3d 2d序列动画代码
  9. 深入浅出话XAML-学习笔记
  10. linux内核分析之内存管理