​LeetCode刷题实战442:数组中重复的数据

本文介绍了一种高效解决LeetCode中数组中重复数据问题的方法。通过原地修改数组值,利用数组下标作为哈希值,实现O(n)时间复杂度且仅使用常量额外空间的要求。

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

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 数组中重复的数据,我们先来看题面:

https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。

找到所有出现两次的元素。

你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例

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

输出:
[2,3]

解题

哈希法:以原数组的下标作为哈希值,遇到出现一次的数,在这个数所指向的下标处数值变为负数,遇到出现第二次的数时,以它为下标指向的数是负数,以此判断。

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for(int i = 0;i < nums.length;++i){
            int index = Math.abs(nums[i])-1;
            if(nums[index] < 0){
                res.add(index+1);
            }else if(nums[index] > 0){
                nums[index] *= -1; 
            }
        }
        return res;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-440题汇总,希望对你有点帮助!

LeetCode刷题实战441:排列硬币

2eac05ccd2ced768147c032a1eeae1d7.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值