LeetCode

链接

217. Contains Duplicate

题意

给定一个数组,只要其中有元素重复,返回true,否则false

思路

利用set的性质即可

代码

Java:

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set set = new HashSet();
        for (int n : nums) {
            set.add(n);
        }
        if (set.size() == nums.length) return false;
        return true;
    }
}

// 类似的
public  boolean containsDuplicate(int[] nums) {
    Set<Integer> set = new HashSet<Integer>();
    for(int i : nums)
        if(!set.add(i)) // 若元素存在,add方法将返回false
	    return true; 
    return false;
}
原文地址:https://www.cnblogs.com/zyoung/p/6860194.html