217. Contains Duplicate
来源:互联网 发布:浙江省软件协会 编辑:程序博客网 时间:2024/05/04 15:18
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.
中文:给你一个数组,判断里面有没有重复的元素。这道题有好几种可以的解法:
This problem seems trivial, so lets try different approaches to solve it:
Starting from worst time complexity to the best one:
Time complexity: O(N^2), memory: O(1)
The naive approach would be to run a iteration for each element and see whether a duplicate value can be found: this results in O(N^2) time complexity.
public boolean containsDuplicate(int[] nums) { for(int i = 0; i < nums.length; i++) { for(int j = i + 1; j < nums.length; j++) { if(nums[i] == nums[j]) { return true; } } } return false;}
Time complexity: O(N lg N), memory: O(1) - not counting the memory used by sort
Since it is trivial task to find duplicates in sorted array, we can sort it as the first step of the algorithm and then search for consecutive duplicates.
public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for(int ind = 1; ind < nums.length; ind++) { if(nums[ind] == nums[ind - 1]) { return true; } } return false;}
Time complexity: O(N), memory: O(N)
Finally we can used a well known data structure hash table that will help us to identify whether an element has been previously encountered in the array.
public boolean containsDuplicate(int[] nums) { final Set<Integer> distinct = new HashSet<Integer>(); for(int num : nums) { if(distinct.contains(num)) { return true; } distinct.add(num); } return false;}
- 217. Contains Duplicate
- LeetCode 217. Contains Duplicate
- [leetcode] 217.Contains Duplicate
- 217.Contains Duplicate
- 【leetcode】217. Contains Duplicate
- 【Leetcode】217. Contains Duplicate
- [LeetCode]217. Contains Duplicate
- 217. Contains Duplicate LeetCode
- 217. Contains Duplicate
- LeetCode 217. Contains Duplicate
- 217. Contains Duplicate
- 217. Contains Duplicate
- 217. Contains Duplicate
- [LeetCode]217. Contains Duplicate
- 【LeetCode】217. Contains Duplicate
- 217. Contains Duplicate
- 217. Contains Duplicate
- leetcode 217. Contains Duplicate
- Qt 内存管理机制
- iBeacon 工作原理
- 关于eclipse注释模板更改
- ubuntu查看系统的信息
- Java动态代理实现
- 217. Contains Duplicate
- [bigdata]小象幫幫忙,Hadoop 能幫什麼忙?
- 最近做网页留下的一些记录吧(关于DIV布局)
- React Native for Android 接入实践
- sklearn学习笔记2 Feature_extraction库
- DIY BROADCAST : How to build your own Internet TV Channel with Open-Source & other goodies
- MyBatis第六步、与Spring MVC集成
- 林轩田机器学习基石——Non-Separable Data
- WampServer 2.5设置手机访问(403 Forbidden错误解决方法)