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

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

一、题目描述

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

输入:nums = [4,3,2,7,8,2,3,1]
输出:[5,6]

示例2

输入:nums = [1,1]
输出:[2]

二、解题思路

使用数组记录数,因为数组长度为n。且数组中的每个数组小于等于n。可以使用hash表记录每一个数组中的数。然后遍历0-n,如果哈希表中没有出现,就是消失的数组。

三,解题方法

方法1(数组)
使用一个数组,直接在原数组中修改值,遍历源数组,将数组的值,在作为原数组的索引,原地加上n,再使用一个for循环,如果其值,小于等于n,就说明没有出现过,因为出现过的都被加上n。
代码实现:

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {

        int n = nums.length;
        for(int i=0 ;i<n; i++){
            int x = (nums[i]-1)%n;
            nums[x] += n;
        }
        
        List<Integer> list = new ArrayList<>();
        
        for(int i=0 ;i<n; i++){
            if(nums[i] <= n){
                list.add(i+1);
            }
        }

        return list;
    }
}
posted @ 2022-12-03 15:57  z_coding  阅读(135)  评论(0)    收藏  举报