美文网首页
LeetCode: 存在重复元素

LeetCode: 存在重复元素

作者: 慕剑璃 | 来源:发表于2018-08-12 23:44 被阅读23次

存在重复元素

English Description


给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。


Example 1

输入: [1,2,3,1]
输出: true

Example 2

输入: [1,2,3,4]
输出: false

Example 3

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true


Answer Here

/**
 * @author Loucianus
 */
public class Duplicates {

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

Thinking

  • 利用Set 集合的特性。

空间复杂度 : O(n)
时间复杂度 : O(n)

相关文章

网友评论

      本文标题:LeetCode: 存在重复元素

      本文链接:https://www.haomeiwen.com/subject/bqnebftx.html