力扣 442. 数组中重复的数据

题目

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。
找到所有出现两次的元素。
你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-duplicates-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

方法1:模拟
Python实现

利用counter来计数

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        counter = collections.Counter()
        out = list()
        for num in nums:
            counter[num] += 1
        for k, v in counter.items():
            if v == 2:
                out.append(k)
        out.sort()
        return out

在这里插入图片描述

Java实现:HashSet
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        Set<Integer> set = new HashSet<>();

        for (int num : nums) {
            if (!set.add(num)) res.add(num);
        }
        return res;
    }
}

在这里插入图片描述

方法2:鸽笼法
Java实现
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int idx = Math.abs(nums[i]) - 1;
            if (nums[idx] > 0) nums[idx] *= -1;
            else {
                res.add(idx + 1);
            }
        }
        return res;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值