【力扣热题100】[Java版] 刷题笔记-448. 找到所有数组中消失的数字

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

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

解题思路

依据题目,有两种解题方式:

第一种是暴力破解,直接创建一个1到n的数组,与传入的数组对比,利用数组自带的函数,得出数组中消失的数字;(数组长度很长时,会超时)

第二种:在数据中判断数字是否为正确位置,如果是,则不需要修正,如果不是,则与正确位置的数字进行交换,直到遍历完所有数据;再进行第二次遍历新的数组,记录位置不正确的数字。

第三种:是看的其他人的解法,很巧妙,整体也是遍历两次数组,第一次遍历,通过数组的数字 x ,判断 x-1 是否有数字且数字大于1, 则将该位置数字 *-1 并赋值给 x-1 位置,这里乘 -1是进行标记,表示数字存在;第二次遍历新数据,数组中大于0的数字存入结果,即是数组中没有的数字。

解题过程

第一种:

java 复制代码
class Solution {
    // 数组长度很大时会超时
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> a = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            a.add(i + 1);
        }
        for (int j = 0; j < nums.length; j++) {
            a.remove(Integer.valueOf(nums[j]));
        }
        return a;
    }  

}

第二种:

java 复制代码
class Solution {
   
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
        int n = nums.length;
        // 交换位置,如果位置正确 或者数值与对应的位置数值相同,则不需要交换
        int i = 0;
        while (i < n) {
            if (nums[i] == i + 1) {
                i++;
                continue;
            }
            int index = nums[i] - 1;
            if (nums[i] == nums[index]) {
                i++;
                continue;
            }
            // 交换位置
            int temp = nums[i];
            nums[i] = nums[index];
            nums[index] = temp;
        }

        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != j + 1) {
                res.add(j + 1);
            }
        }
        return res;
    }
}

第三种:

java 复制代码
public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> res = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            // 获取当前值,如果当前值作为索引(值-1)存在对应的值,则赋予负值
            int num = Math.abs(nums[i]);
            int index = num - 1;
            if (nums[index] > 0) {
                nums[index] *= -1;
            }
        }
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] > 0) {
                res.add(j + 1);
            }
        }
        return res;
    }
相关推荐
yyy(十一月限定版)几秒前
CF2131D Arboris Contractio
算法
栈溢出了2 分钟前
VS Code Python 自动导包失效排查笔记
开发语言·笔记·python
朝朝辞暮i9 分钟前
C++ 第 28 课:Lambda 表达式
开发语言·c++·算法
代码什么用12 分钟前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.16 分钟前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode
释厄62326 分钟前
BSD 基础论——不要忘记连接·不要停滞循环·AI基础算法
人工智能·算法
yi01138 分钟前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b40 分钟前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
释厄62344 分钟前
AI犯错即异质论——正确认知=免疫与安全防控技术算法
大数据·算法·安全
漂流瓶jz1 小时前
UVA-12545 比特变换器 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·aoapc·算法竞赛入门经典·uva·12545