给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
解答方法:
这里巧用了set插入时如果新元素已经存在,则会新增报错
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> numsSet = new HashSet<Integer>();
for(int i:nums){
boolean flag = numsSet.add(i);
if(!flag){
return true;
}
}
return false;
}
}
Way cool! Some very valid points! I appreciate you penning this write-up plus the rest of the site is extremely good. Perri Stephanus Ramah
Way cool! Some very valid points! I appreciate you penning this post and also the rest of the site is also very good. Norean Malvin Namara
Very good blog post. I absolutely love this site. Keep it up!
Very good blog post. I absolutely love this site. Keep it up!
This site was? how do I say it?
Relevant!! Finally I have found something that helped me.
Thank you!
You should take part in a contest for the most effective blogs on the web. I will recommend this web site!
Overall, I think your blog is a fantastic resource and I will definitely be recommending it to others. Keep up the great work!