美文网首页
442. 数组中重复的数据

442. 数组中重复的数据

作者: 编程小王子AAA | 来源:发表于2020-07-27 23:14 被阅读0次

给定一个整数数组 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(Math.abs(nums[i]));
                continue;
            }
            nums[index]=-nums[index];
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:442. 数组中重复的数据

      本文链接:https://www.haomeiwen.com/subject/nbqxrktx.html