solution:
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; // index start from 0 nums[m] = nums[m]>0 ? -nums[m] : nums[m]; } vector<int> res; for(int i = 0; i<len; i++) { if(nums[i] > 0) res.push_back(i+1); } return res; } };
The basic idea here is to label all appeared numbers in the array. Since we don't want to introduce extra space and given all numbers are positive(from 1 to n), negate the value in the corresponding position is one choice. Ex, for input like [1, 2, 2], after the first sweep, it becomes [-1, -2, 2]. At position index=2, there is a positive value, which means it corresponding value 3 is not showing.
Hope this simple example gives you some lead :-)
这个答案有点启发性,留存。