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

/*
思路:
因为时间复杂度为O(n),所以不能
因为空间复杂度为O(1),所以不能使用额外的数组或者其他的数据结构来存放,只能在原来的数组的基础上进行修改
在这里,如果第一个数字是4,我们把对应下标为3的那个数置为负数,一直循环到最后
最后循环遍历修改过的数组,如果对应下标这个数为负数说明数等于下标+1这个数出现过
*/
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
        if(nums == null){
            return null;
        }
        
        List<Integer> list = new ArrayList<>();
        
        for(int i = 0; i < nums.length; i++){
            int index = Math.abs(nums[i]) - 1;
            // if(nums[index] > 0){
            //     nums[index] = -nums[index];
            // }
            nums[index] = ((nums[index] > 0) ? -nums[index] : nums[index]);
        }
        
        for(int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                list.add(i + 1);
            }
        }
        
        return list; 
        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32682177/article/details/81872084