Contains Duplicate 解答
2015-09-11 04:03
288 查看
Question
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.Solution 1 HashMap
Time complexity O(n), space cost O(n)public class Solution { public boolean containsDuplicate(int[] nums) { Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); int length = nums.length; if (length <= 1) return false; for (int i = 0; i < length; i++) { if (counts.containsKey(nums[i])) return true; else counts.put(nums[i], 1); } return false; } }
Solution 2 Set
Time complexity O(n), space cost O(n)public class Solution { public boolean containsDuplicate(int[] nums) { int length = nums.length; if (length <= 1) return false; Set<Integer> set = new HashSet<Integer>(); for (int i : nums) { if (!set.add(i)) return true; } return false; } }
相关文章推荐
- Communications link failure,The last packet succes
- zabbix 邮件报警 -- sendmail
- 15_09_10 contains 错误用法
- Git push 报错 "error: failed to push some refs to " 解决
- Failed to complete gradle execution.
- int main( int argc, char ** argv)在VS2008中的配置的一个实例
- Rails进阶参考
- 使用Genymotion安装APK出现错误INSTALL_FAILED_CPU_ABI_INCOMPATIBLE的解决办法
- LEETCODE-Contains Duplicate
- Leet Code 11 Container With Most Water
- Container With Most Water
- http://jingyan.baidu.com/article/08b6a591f0fafc14a9092275.html
- linker command failed with exit code 1 错误的解决
- POJ 1840 Brainman(逆序对数)
- Package的Transaction处理之一:使用Connetion的属性RetainSameConnection
- httpd: Could not reliably determine the server's fully qualified domain name
- email program (客户端)演变过程有感
- Email发展历史
- 多线程中让main方法最先开始,最后结束的简单例子
- baiduPOP3/SMTP设置