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.

Example:

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

Output:
[5,6]
意思就是给一个长度为n的数组,数组里的元素都≥1,≤n,就是 1 ≤ a[i] ≤  n  ( n  = size of array),[1,n]中的有些数字可能不在数组中出现,找出哪些数字没有出现。

代码如下:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> test;   //用于找出[1,n]中哪些数字没有出现
        vector<int> ans;    //将没有出现的数字放入ans
        for(int i=0;i<=nums.size();i++){    //将test置零,且test的长度为n+1,注意i要<=nums.size(),不能只<
            test.push_back(0);
        }
        for(int i=0;i<nums.size();i++){
            if(!test[nums[i]]){
                test[nums[i]]++;
            }
        }
        for(int i=1;i<=nums.size();i++){  //同样注意i要<=nums.size(),不能只<,且i从1开始遍历,因为原数组不包含0
            if(!test[i]){
                ans.push_back(i);
            }
        }
        return ans;
    }
};

用时142ms,击败了59.57%的c++程序。
我在关于这题的讨论里看到了一种更好的解法,时间复杂度为O(n),空间复杂度为O(1),代码如下:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int len = nums.size();
        for(int i=0; i<len; i++) {
            int m = abs(nums[i])-1; // index start from 0
            nums[m] = nums[m]>0 ? -nums[m] : nums[m];
        }
        vector<int> res;
        for(int i = 0; i<len; i++) {
            if(nums[i] > 0) res.push_back(i+1);
        }
        return res;
    }
};

含义就是如果如果[1,n]之间某一个数字出现了,就将nums[i-1]=-nums[i-1],将nums[i-1]变成负数用来说明i出现了,处理完之后,再遍历一遍nums,如果nums[i]为正,则就说明i+1未出现。

原作者的解释:

The basic idea here is to label all appeared numbers in the array. Since we don't want to introduce extra space and given all numbers are positive(from 1 to n), negate the value in the corresponding position is one choice. Ex, for input like [1, 2, 2], after the first sweep, it becomes [-1, -2, 2]. At position index=2, there is a positive value, which means it corresponding value 3 is not showing.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值