442. Find All Duplicates in an Array--找到数组中出现两次的数字

本文介绍了一种在不使用额外空间的情况下查找数组中重复元素的方法,并提供两种解决方案:一种使用HashMap统计出现次数,另一种利用数组特性直接在O(n)时间内找出重复项。

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

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

题目的意思很明显了,找到数组中出现次数为2的数字,返回这些数字即可。我用了HashMap,将每个数字和它出现的次数作为一个映射,然后遍历map,将符合条件的值添加到list中即可。虽然AC了,但是只击败了4.8%的提交结果==,代码如下:

        List<Integer> list = new ArrayList<Integer>();
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
        	if(!map.containsKey(nums[i])){
        		map.put(nums[i], 1);
        	}
        	else{map.put(nums[i],map.get(nums[i])+1);}
        	
        }
        for(Map.Entry<Integer,Integer> m:map.entrySet())  
            if(m.getValue()==2){
            	list.add(m.getKey());
            	}
        return list;
网上看了另一种方法,充分应用条件,因为题目中说明,这些数字 1 ≤ a[i] ≤  n  ( n  = size of array),并且一些数字出现2次,其他的出现1次,那么,新建一个数组,把nums中的数字nums[i]放到temp中索引为nums[i]的地方,如果temp[nums[i]]=nums[i],说明nums[i]之前已经出现过,那么就将它加入到res这个列表中,提交结果为60%左右。代码如下:

    int [] temp = new int [nums.length+1];
		List<Integer> res = new ArrayList<>();
		for(int i=0;i<nums.length;i++){
			if(temp[nums[i]]==nums[i]){res.add(nums[i]);}
			else{temp[nums[i]]=nums[i];}
		}
		return res;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值