Leetcode--Java--448. Find All Numbers Disappeared in an Array

这篇博客探讨了一种在给定数组中找出缺失数字的算法问题。通过将出现过的数字标记为负数,然后遍历数组寻找未被标记的正数,可以有效地找到[1,n]范围内缺失的整数,且该方法不使用额外空间,具有O(n)的时间复杂度。代码示例使用Java实现,展示了如何高效地解决此类问题。
摘要由CSDN通过智能技术生成

题目描述

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

样例描述

Example 1:

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

Input: nums = [1,1]
Output: [2]
 

Constraints:

n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
 

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

思路

  1. 标记的思路,不用额外空间。将出现过的数对应的下标位置数置为负数,然后在扫描一遍,正数的位置对应的下标加1就是消失的数字
  2. 注意 下标从0开始,置负数时要减一,然后先取绝对值,遍历到这个数时可能该数被置为了负数。 最后,因为有的数出现多次,先判断该位置是否大于0,避免已经负数了又被重复置为正数

代码

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
         //将出现过的数作为下标对应的数  置为负数
         for (int x: nums){
             //换绝对值,因为可能被置为负数了
            x = Math.abs(x);
            if (nums[x - 1] > 0) nums[x - 1] *= -1;
         }
         //寻找不是负数的就是消失的
       for (int i = 0; i < nums.length; i ++){
           //下标是0开始的,对应数要加一
           if (nums[i] > 0) res.add(i + 1);
       }
       return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值