Array:Find All Numbers Disappeared in an Array

本文介绍了一种在不使用额外空间且O(n)时间内找出数组中缺失元素的方法。通过正负号标记法,循环数组并调整元素符号,最终确定哪些元素未出现在原数组中。

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

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

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

题目大意:

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

寻找所有[1, n]中没有出现在数组中的元素。

可以不使用额外空间并在O(n)运行时间求解吗?你可以假设返回列表不算额外空间。

解题思路:

需要注意的是数组元素大小在1到n之间,n为数组长度。初做时没有注意到这点。思路是正负号标记法,循环数组,令nums[abs(nums[i])-1] = -nums[abs(nums[i])-1],第二次循环中没有被标记为负的元素的索引加上1便是缺失的数。

如数组      [1,2,3,3,5,6]

数组下标为{0,1,2,3,4,5}

缺失了4,因此索引为3的元素将不会被标记为负,所以只需找到所有正数的索引值加上1即可。

    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            int val = Math.abs(nums[i]) - 1;
            if (nums[val] > 0) 
                nums[val] = -nums[val];
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0)
                res.add(i + 1);
        }
        return res;
    }

 

 

转载于:https://www.cnblogs.com/ltchu/p/6410512.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值