算法列表

442.数组中重复的数据 中等

布莱克2026-03-14 22:06数组

问题:

给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 最多两次 。请你找出所有出现 两次 的整数,并以数组形式返回。

你必须设计并实现一个时间复杂度为 O(n) 且仅使用常量额外空间(不包括存储输出所需的空间)的算法解决此问题。

示例 1:

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

示例 2:

输入:nums = [1,1,2]
输出:[1]

示例 3:

输入:nums = [1]
输出:[]

回答:

数组的数字范围在[1-n]之间,得到当前索引对应值后-1,否则如果数字为数组长度,会超出找不到

使用负数标记访问过的位置

如果再次访问时为负数,代表是第二次出现

var findDuplicates = function(nums) {
    let res = [];
    for (let i = 0; i < nums.length; i++) {
        let index = Math.abs(nums[i]) - 1;
        if (nums[index] < 0) {
            res.push(Math.abs(nums[i])); //推入当前值
        } else {
            nums[index] = -nums[index]
        }
    }
    return res;
};


assistant