Leetcode:442. Find All Duplicates in an Array 找数组中的重复数字

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:
Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]
题目分析:拿着题目你或许会觉得奇怪?这个条件是干啥的?1 ≤ a[i] ≤ n (n = size of array)????
是不是觉得这个条件没什么用?
但是!!!到最后我才发现这个题目的这个条件非常的重要,如果没有这个条件那么就很难在O(N)的时间复杂读内解决这个问题。
题目解决办法分析:
你会发现所有元素的大小一定是在数组的长度范围内,那么我们可以进行如下的操作:
来看一种正负替换的方法,这类问题的核心是就是找nums[i]和nums[nums[i] - 1]的关系,我们的做法是,对于每个nums[i],我们将其对应的nums[nums[i] - 1]取相反数,如果其已经是负数了,说明之前存在过,我们将其加入结果res中即可,参见代码如下:[4,3,2,7,8,2,3,1]
比如这里这个数组 执行顺序如下

            //nums[3] = -7;
            //index = 2
            //nums[2] = -2
            //index = 1 
            //nums[1] = -3
            //index = 6
            //nums[6] = -2
            //index = 7
            //nums[7] = -3
            //index = 1
            //现在 发现nums[1] = -3 < 0 说明这个数字存在过2加入
            //index = 2
            //现在 发现nums[2] = -2 < 0 说明这个数字存在过3加入
            //index = 0
            //nums[0] = 4

Java代码如下:

public static List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; ++i) {
            int index = Math.abs(nums[i])-1;
            if (nums[index] < 0)
                res.add(Math.abs(index+1));
            nums[index] = -nums[index]; 
        }
        return res;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值