LeetCode 217. Contains Duplicate
2016-02-17 14:11
465 查看
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.
分析:查找整型数组中是否有重复的数据。此前的Single
Number系列问题中利用集合(Set)的数据不可重复的性质来判断是否存在重复的数据。本题也可以利用Set的一些性质,两种解法,分别如下:
代码:
1.判断数据能否加入到集合,从而判断有无重复数据。
2.判断数据在集合中是否存在,从而判断有无重复数据
解法1耗时更少。
twice in the array, and it should return false if every element is distinct.
分析:查找整型数组中是否有重复的数据。此前的Single
Number系列问题中利用集合(Set)的数据不可重复的性质来判断是否存在重复的数据。本题也可以利用Set的一些性质,两种解法,分别如下:
代码:
1.判断数据能否加入到集合,从而判断有无重复数据。
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i <nums.length; i++){ if(!set.add(nums[i])){ return true; } } return false; } }
2.判断数据在集合中是否存在,从而判断有无重复数据
public class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<Integer>(); for(int x : nums){ if(set.contains(x)) return true; set.add(x); } return false; } }
解法1耗时更少。
相关文章推荐
- Failed to locate or generate matchin signing assets
- process launch failed: Security
- Spark技术内幕:Master基于ZooKeeper的High Availability(HA)源码实现
- Login with RMAN immediately fails with ORA-04031, ORA-06508
- HackerRank "Training the army" - Max Flow
- Something about the microsoft HttpContext domain design
- OORA-38760: This database instance failed to turn on flashback database
- JetBrains系列产品激活
- Error:executing aidl:return code 1
- 内网访问baidu慢且丢包严重
- raid相关知识
- nova availability-zone使用
- 1079. Total Sales of Supply Chain (25)
- 关于报错:Failed to resolve: 'de.greenrobot:eventbus:2.4.0' 'de.greenrobot:greendao:2.1.0'等问题的解决办法
- 如何创建一个Plain TableView With Section And Index
- 跨进程访问(AIDL服务)-更新中
- Rails 控制器
- Async Await异步调用WebApi
- leetcode 182. Duplicate Emails
- Unix Study之--AIX系统监控工具tops