leetcode 217 Contains Duplicate

本文介绍了一种检测数组中是否存在重复元素的方法。通过两种途径实现:一是利用HashMap存储元素及其出现次数;二是对数组进行预排序后检查相邻元素是否相同。

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

题目详情

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

思路

  • 这道题理解起来比较简单,首先还是要注意一下边界条件/异常输入,对于长度小于等于1的数组做一个直接的返回
  • 对于这种要考虑数组中元素的重复的问题,就很容易想到hashmap,key就是元素的值,value可以表示元素的个数,对于已经存在的key,直接返回true,但是这种解法需要额外O(n)的空间
  • 在使用hashmap求解的过程中,我意识到了这个方法还是想的复杂了,数组元素的重复性问题通常还有一种思路就是数组的预排序
  • 先对输入数组进行预排序,然后只需要比较数组和它相临的元素是否相等就可以了

解法一 HashMap

    public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length <= 1){
            return false;
        }     
        HashMap<Integer,Integer> count = new HashMap<Integer, Integer>();
        count.put(nums[0], 1);
        
        for(int i = 1;i<nums.length;i++){
            int tempKey = nums[i];
            if(count.get(tempKey) != null ){
                return true;
            }else{
                count.put(tempKey, 1);
            }
        }
        
        return false;
    }

解法二 预排序算法

    public boolean containsDuplicate(int[] nums) {
        int length = nums.length;
        if(length <= 1){
            return false;
        } 
        Arrays.sort(nums);
        for(int i=0 ;i<length-1;i++){
            if(nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值