leetcode [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]

题目大意: 

  给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。找到所有在 [1, n] 范围之间没有出现在数组中的数字。

理  解:

    利用  1 ≤ a[i] ≤ n 的范围,出现的数字找到它对应的下标,将下标对应值变为负数。

  再次遍历数组,若值大于0,则元素i+1未出现。

代 码 C++:

class Solution {
public: // 利用1<=a[i]<=n
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int index; 
        vector<int> res;
        for(int i=0;i<nums.size();++i){ 
            index = abs(nums[i]) - 1;
            if(nums[index]>0)
                nums[index] *= (-1);  // 表示值index+1 已存在
        }
        for(int i=0;i<nums.size();++i){
            if(nums[i]>0)
                res.push_back(i+1);
        }
        return res;
    }
};

运行结果:

  执行用时 :136 ms, 在所有 C++ 提交中击败了95.32%的用户

  内存消耗 :14.7 MB, 在所有 C++ 提交中击败了97.21%的用户
posted @ 2019-06-30 16:22  lpomeloz  阅读(134)  评论(0编辑  收藏  举报