217. Contains Duplicate
2016-02-23 19:37
435 查看
题目:
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.
我的思路:
使用Java本身的HashSet结构,根据其集合特性保证其中的值不会重复。
代码:public class Solution {
public boolean containsDuplicate(int[] nums) {
//进行出错处理
if (nums.length == 0) return false;
//HashSet是集合,不允许出现重复的数值
HashSet<Integer> appeared = new HashSet<>();
for(int n : nums) {
if (!appeared.add(n)) return true;
}
return false;
}
}
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.
我的思路:
使用Java本身的HashSet结构,根据其集合特性保证其中的值不会重复。
代码:public class Solution {
public boolean containsDuplicate(int[] nums) {
//进行出错处理
if (nums.length == 0) return false;
//HashSet是集合,不允许出现重复的数值
HashSet<Integer> appeared = new HashSet<>();
for(int n : nums) {
if (!appeared.add(n)) return true;
}
return false;
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树