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

LeetCode-Contains Duplicate 217

2015-10-10 21:42 411 查看
Problem:

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.

analysis:

方案一:遍历数组中的每一个数,寻找这个数之后的数是否和这个数相同,如果相同则返回true,遍历之后没有相同的返回false。

该方法适合数组小的情况,因为耗时比较严重。

方案二:利用hashmap,遍历数组,将数组中的每一个数加入map中,如果map中没有这个数就加入下一个数,如果有这个数则返回true,遍历完之后返回false。

该方法比较适合数组大的情况,查找效率较高。

anwser:

1 利用数组查找(其实应该先排序,然后查找相邻两个数是否相同)

public class Solution {
public boolean containsDuplicate(int[] nums) {
int temp;
for(int i=0;i<nums.length-1;i++){
temp=nums[i];
for(int j=i+1;j<=nums.length-1;j++){
if(temp==nums[j]) return true;
}
}
return false;
}
}


2 利用HashSet

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