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.

class Solution {
public:
    vector findDisappearedNumbers(vector &nums) {
        // nums[i] = i+1 这个数才是放在了正确的位置上 否则就反复交换
        if(nums.empty())    return {};
        vector ret;
        nums.insert(nums.begin(), 0); // 哨兵
        for(int i=1;i

此外 还有一种思路是 设flag (用负数的形式表示) 

对于每个数字nums[i],如果其对应的nums[nums[i] - 1]是正数,我们就赋值为其相反数,如果已经是负数了,就不变了,那么最后我们只要把留下的整数对应的位置加入结果res中即可

你可能感兴趣的:(leetcode)