217. Contains Duplicate

本文介绍了一种使用HashSet解决LeetCode题目中数组重复元素检测的方法。通过实例展示,如输入[1,2,3,1],输出为true;输入[1,2,3,4],输出为false。解决方案利用了HashSet的add方法,当尝试添加已存在的元素时,会返回false,从而判断数组中是否存在重复元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天刷 leetcode  "4. Median of Two Sorted Arrays",半天没看懂log(m +n) 算法的具体细节,十分懊恼,做一道简单题放松一下。这道题去北邮面试的时候还考过,当初直接用一个数组s,用index存input数组的值,用s[index] ,存储对应的下标,如果发现s[index]不是0,则说明已经出现,故重复。(默认index从1开始)

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.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

solution:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int len = nums.length;
        for(int num:nums){
            //add方法 插入成功返回true,有冗余数据失败返回false
            if(!set.add(num)){
                return true;
            }
        }
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值