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

程序IT圈

共 1259字,需浏览 3分钟

 ·

2021-11-19 05:34

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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 findDuplicates(int[] nums) {
        List 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:排列硬币



浏览 36
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报