您的位置:首页 > 大数据 > 人工智能

Leetcode Contains Duplicate

2015-09-22 00:53 597 查看
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.

解题思路:

判断array里是否有重复,就想到一种不能有重复的数据结构set, 如果已经有了这个值,则return true, 否则就加进这个set.

当然,set 也有不同的用法。写了两种。

Java code:

public boolean containsDuplicate(int[] nums) {
Set<Integer> values = new HashSet<Integer>();
for(int i=0; i< nums.length; i++) {
if(values.contains(nums[i])){
return true;
}
values.add(nums[i]);
}
return false;
}


或者:

public boolean containsDuplicate(int[] nums) {
Set<Integer> values = new HashSet<Integer>();
for(int i=0; i< nums.length; i++) {
if(!values.add(nums[i])){
return true;
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: