力扣leetcode之Java刷题448找到所有数组中消失的数字

448. 找到所有数组中消失的数字

题目:

给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。

思路:

在这里插入图片描述
遍历数组,将每个数字交换到它理应出现的位置上,下面情况不用换:
  当前数字本就出现在理应的位置上,跳过,不用换。
  当前数字理应出现的位置上,已经存在当前数字,跳过,不用换。
再次遍历,如果当前位置没对应正确的数,如上图索引 4、5,则将对应的 5、6 加入 res。

代码:

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        int i = 0;
        //遍历数组,将每个数字交换到它理应出现的位置上
        while (i < nums.length) {
            //当前的数字就出现在它理应的位置上,不用换
            if(nums[i] == i+1) {
                i++;
                continue;
            }
            int should = nums[i] - 1;
            //当前的数字理应出现的位置上,已经存在当前数字,不用换
            if(nums[i] == nums[should]) {
                i++;
                continue;
            }
            int temp = nums[i];
            nums[i] = nums[should];
            nums[should] = temp;
        }
        //再次遍历,如果当前位置不对应数字,则把当前位置的索引加入res
        for (int j = 0; j < nums.length; j++) {
             if (nums[j] != j + 1) {
                res.add(j+1);
            }
        }
        return res;
    }
}

转载:

如有冒犯请私信我删除
链接:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/solution/shou-hua-tu-jie-jiao-huan-shu-zi-zai-ci-kzicg/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值