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

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

示例 1:

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

示例 2:

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

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
/**
 * @author zhang
 * 思路:
 * 用Set集合实现,Set用于存储不重复的元素集合
 * 如果add不了说明已经add过,就是重复了,返回true
 * 
 */
public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }

链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x248f5/

最后修改:2022 年 01 月 07 日
点个赞或者请作者喝杯咖啡