LeetCode 448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

一、问题描述

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

二、输入输出

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

三、解题思路

  • 还有一道是找没有出现的数字的题442. Find All Duplicates in an Array
  • 这两道题很像,难点在于时间复杂度为o(n) 空间复杂度为o(1). 快速排序的最好时间复杂度是o(nlogn) 最差是o(n2) 所以不能排序,而且需要在原来的数组上进行修改。
  • 这里面存在一个映射关系,即第i个元素(从0开始) 对应的值为(i+1) 这样正好将1-n从小到大的排列到数组上。
  • 核心思想就是:我们把遍历到的nums[i] 对应的位置的值设置为原值的相反数,来表示这个nums[i]是否已经出现过了,比如:curVal = nums[i]我们期望他在的位置是expectIndex = nums[i] - 1 然后把expectIndex位置的数设置为负数nums[expectIndex] = - nums[expectIndex], 来表示我们刚刚搜索过nums[i]了,这个数字是存在的。
  • 如果是找重复出现的数字,那么只需要判断nums[expectIndex]是不是负的就行了。是负的,说明之前出现过expectIndex + 1这个值,现在又出现了,所以重复了。
  • 如果是找没有出现的数字,只需要重新遍历一遍数组,哪些index对应的nums[index]为正,则说明对应index的值index+1没有出现过,如果出现过他应该被我们设置为负的了。
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
                int n = nums.size();
        vector<int> ret;
        for (int i = 0; i < n; ++i) {
            int curVal = nums[i];
            int expectIndex = abs(curVal) - 1;
            if(nums[expectIndex] > 0)
                nums[expectIndex] = - nums[expectIndex];
        }
        for (int i = 0; i < n; ++i) {
            if(nums[i] > 0)
                ret.push_back(i+1);
        }
        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值