leetcode 448. 找到所有数组中消失的数字-java题解

题目所属分类

原题链接

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

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

题解

1、遍历每个元素,对索引进行标记,将对应索引位置的值变为负数;
2、遍历下索引,看看哪些索引位置上的数不是负数的,位置上不是负数的索引,对应的元素就是不存在的。

class Solution {
    
    
    public List<Integer> findDisappearedNumbers(int[] nums) {
    
    
         List<Integer> res = new ArrayList<>();
         for(int x : nums){
    
    
             x = Math.abs(x);
             //下标是从0-1  所以要x-1
             if(nums[x-1] > 0) nums[x-1] *= -1 ;
         }
         for(int i = 0 ; i < nums.length ; i++){
    
    
             if(nums[i] > 0 ) res.add(i+1);
         }
         return res; 
    }
}

写法2:

class Solution {
    
    
    public List<Integer> findDisappearedNumbers(int[] nums) {
    
    
        List<Integer> ans = new ArrayList<Integer>();
        int n = nums.length;
        for(int i = 0;i < n;i ++)
        {
    
    
            int idx = Math.abs(nums[i]) - 1;
            if(nums[idx] > 0) nums[idx] *= -1;
        }

        for(int i = 0;i < n;i ++)
        {
    
    
            if(nums[i] > 0) ans.add(i + 1);
        }
        return ans;
    }
}

 

猜你喜欢

转载自blog.csdn.net/qq_41810415/article/details/128745873