217. Contains Duplicate

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.

给定整数数组,查找是否包含重复的数。如果任何一个数在数组中出现了至少两次,函数返回true;若每个数互不相同则返回false。

学习一下jmnarloch的做法:

public boolean containsDuplicate(int[] nums) {

        return nums.length != Arrays.stream(nums)
                .distinct()
                .count();
    }
关于stream的介绍参考http://blog.csdn.net/happyheng/article/details/52832313
Java8中提供了Stream对集合操作作出了极大的简化,学习了Stream之后,我们以后不用使用for循环就能对集合作出很好的操作。

我的方法,时间复杂度和内存都是O(n)

import java.util.HashSet;
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set=new HashSet<Integer> ();
for(int i=0;i<nums.length;i++) {
if(set.contains(nums[i]))
return true;
else
set.add(nums[i]);
}
return false;
}
}

posted @ 2018-02-22 11:59  同销万古愁  阅读(87)  评论(0编辑  收藏  举报