[LeetCode]448. Find All Numbers Disappeared in an Array(查找数组中消失的所有数字)

来源:互联网 发布:比特币挖矿软件下载 编辑:程序博客网 时间:2024/05/16 19:38

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.
题目大意:
(谷歌翻译)给定一个整数数组,其中1≤a[i]≤n(n =数组大小),一些元素出现两次,其他元素出现一次。
查找[1,n]包含的所有不显示在此数组中的元素。
你能做它没有额外的空间和在O(n)运行时? 您可以假定返回的列表不计为额外的空间。

Example:

Input:  [4,3,2,7,8,2,3,1]Output:  [5,6]

思路:

  • 由于题目中有数组中所有数字都大于等于1且小于等于n,而n为数组长度。
  • 可以以数组下标作为索引标记哪些数字出现过,标记方法为将出现数字对应下标的数字标为负数。
C++class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        //以数组下标作为索引标记哪些数字出现过,标记方法为将出现数字对应下标的数字标为负数        int length = nums.size();        vector<int> res;        for(int i=0;i<length;i++){            //计算出数组中出现的数字x的下标形式,则下标为index=|x| -1,            //可将数组a中得a[index]标为负数来标记数字x出现在数组中            int a = abs(nums[i]) - 1;//abs()返回绝对值            if(nums[a]>0)                nums[a] *= -1;        }        //若数组中某数字已为负数,说明该数字在数组中出现过        //最终遍历数组,若a[i]为正数,表明数字 i + 1在数组中没有出现过        for(int i=0;i<length;i++){            if(nums[i] > 0)                res.push_back(i+1);        }        return res;    }};

注意:

  • 参考http://blog.csdn.net/liujiayu1015/article/details/53758954
  • int a = abs(nums[i]) - 1;//abs()返回绝对值 发现必须用该函数,不用就会报错
  • 最重要的是不能用额外的空间和时间复杂度O(n),所以只能在原数组中改变数值
0 0
原创粉丝点击