217. Contains Duplicate
来源:互联网 发布:淘宝店铺怎么关注链接 编辑:程序博客网 时间:2024/06/05 03:47
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.
解法一:Language-Java Time-O(n) Space-O(n) Run Time-15ms
解题思路:
利用HashMap记录每个元素出现的次数,这种解法有时候会超时
public class Solution { public boolean containsDuplicate(int[] nums) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); boolean bool = false; for(int i = 0; i < nums.length; i ++) { if(map.containsKey(nums[i])) { map.put(nums[i], map.get(nums[i]) +1); //如果出现了两次以上 if(map.get(nums[i]) >= 2) { bool = true; break; } }else { map.put(nums[i], 1); } } return bool; }}
解法二:Language-Java Time-O(n) Space-O(n) Run Time-14ms
解题思路:
利用HashSet存放所有的元素,如果set中元素总个数小于nums中元素的个数,就说明含有重复的元素,这种解法有时也会超时
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i : nums) { set.add(i); } if(set.size() < nums.length) { return true; }else { return false; } }}
解法三:Language-Java Time-O(n) Space-O(n)
解题思路:在解法二的基础上,加入判断是否有一样的元素。
解法三-1.Run Time:14ms 有时会超时
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i : nums) { //如果set中有一样的 if(set.contains(i)) return true; set.add(i); } return false; }}
解法三-2.Run Time:9ms
注:set.add(i)的返回值为boolean类型,如果返回true,说明set中不含元素i,把元素i加入到set中。
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i : nums) { //如果set中有一样的 if(!set.add(i)) return true; } return false; }}
解法四:Language-Java Time-O(nlogn) Space-O(1) Run Time-5ms
解题思路:先排序,然后判断有没有重复的元素
public class Solution { public boolean containsDuplicate(int[] nums) { int count = 0; Arrays.sort(nums); //i从1开始 for(int i = 1; i < nums.length; i ++) { if(nums[i] == nums[i-1]) { return true; } } return false; }}
0 0
- 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
- Android设计之美:MVP模式创建轮播图(Banner)
- dp1.1
- HTML5 data-* 自定义属性
- 1619-7 张良 十月十四号总结 [连续第十四天]
- 小目标
- 217. Contains Duplicate
- C++覆盖(虚函数的实现原理)
- 练习Linux中的vi编辑器
- Android入门第十二篇之Gallery
- 简单DP 总结
- strstr(str1,str2)函数使用时注意事项
- 前端常用的正则表达式大全
- orcale 11G 闪回查询误删数据
- Swift2.3 --> Swift3.0 的变化