LeetCode-Contains Duplicate 217
2015-10-10 21:42
411 查看
Problem:
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.
analysis:
方案一:遍历数组中的每一个数,寻找这个数之后的数是否和这个数相同,如果相同则返回true,遍历之后没有相同的返回false。
该方法适合数组小的情况,因为耗时比较严重。
方案二:利用hashmap,遍历数组,将数组中的每一个数加入map中,如果map中没有这个数就加入下一个数,如果有这个数则返回true,遍历完之后返回false。
该方法比较适合数组大的情况,查找效率较高。
anwser:
1 利用数组查找(其实应该先排序,然后查找相邻两个数是否相同)
2 利用HashSet
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.
analysis:
方案一:遍历数组中的每一个数,寻找这个数之后的数是否和这个数相同,如果相同则返回true,遍历之后没有相同的返回false。
该方法适合数组小的情况,因为耗时比较严重。
方案二:利用hashmap,遍历数组,将数组中的每一个数加入map中,如果map中没有这个数就加入下一个数,如果有这个数则返回true,遍历完之后返回false。
该方法比较适合数组大的情况,查找效率较高。
anwser:
1 利用数组查找(其实应该先排序,然后查找相邻两个数是否相同)
public class Solution { public boolean containsDuplicate(int[] nums) { int temp; for(int i=0;i<nums.length-1;i++){ temp=nums[i]; for(int j=i+1;j<=nums.length-1;j++){ if(temp==nums[j]) return true; } } return false; } }
2 利用HashSet
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i=0;i<nums.length;i++){ if(!set.contains(nums[i])){ set.add(nums[i]); } else return true; } return false; } }
相关文章推荐
- http://blog.csdn.net/liulina603/article/details/8617281
- Codeforces Round #323 (Div. 2) D.Once Again...(582B)
- tools:context=".MainActivity的作用
- LeetCode-Contains Duplicate II
- LightOJ 1138 Trailing Zeroes (III)
- WinMain与WndProc以及窗口诞生过程总结
- CClientDC和CPaintDC、CWindowsDC之间的联系和区别
- *SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
- 17.1.1.4 Obtaining the Replication Master Binary Log Coordinate
- HDU 4810 Wall Painting
- HDU 5228 ZCC loves straight flush
- 生产环境 分区做raid
- failed command: READ DMA
- crossdomain.xml怎么用
- Error Domain=NSCocoaErrorDomain Code=3840解决方法
- 【未完】mail邮件报警系统搭建
- property 描述 之copy assign retain strong weak
- MainData仿Backbone Model式 数据模型记录器
- ALAssetsLibrary的使用问题:获取到ALAsset的thumbnail或者其他属性保存数组,在别地地方为nil的问题处理
- UVA Live Archive 4394 String painter(区间dp)