Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

My first reaction is to have an unlimited length of bit-array, to mark existence. But if no extra mem is allowed, we can simply use 'sign' on each index slot to mark the same info.. it is a common technique.

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> ret;
        int n = nums.size();
        if(!n) return ret;
        
        // Pass 1 - use sign to mark existence.
        for(int i = 0; i < n; i ++)
        {
            int inx = abs(nums[i]) - 1;
            nums[inx] = -abs(nums[inx]);
        }   
        
        // Pass 1 - get all positive
        for(int i = 0; i < n; i ++)
            if(nums[i] > 0)
                ret.push_back(i + 1);
        
        return ret;
    }
};
posted on 2017-01-06 08:31  Tonix  阅读(110)  评论(0)    收藏  举报