leetCode刷题归纳-Array(448. Find All Numbers Disappeared in an Array Add to List)

来源:互联网 发布:美工算平面设计吗 编辑:程序博客网 时间:2024/05/22 09:39

很有意思的思路,采用标记负值的方法解决,如果出现过就标记为负数,最后检测正数的位置,其索引值对应的就是没有出现过的位置。

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]

解决代码:

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;//关于这个地方为什么一定要加绝对值,因为前面的步骤可能把正值变成了负值,索引会错误            nums[m]=nums[m]>0?-nums[m]:nums[m];        }         vector<int> result;        for (int i=0;i<len;i++){            if (nums[i]>0)                result.insert(result.end(),i+1);        }        return result;       }};
0 0
原创粉丝点击