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.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

题目很直观,就不多说了,给出我的很蠢的解答~_~(185ms)
 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4 
 5         unordered_map<int, int> hash;
 6         int n = nums.size();
 7         
 8         for (auto i : nums)
 9         {
10             ++hash[i];
11         }
12         nums.clear();
13         for (int i = 1; i <= n; ++i)
14         {
15             if (hash[i] - 1 == -1)
16             {
17                 nums.push_back(i);
18             }
19         }
20 
21         return nums;
22     }
23 };

贴上一个比较好的解答:

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4         int len = nums.size();
 5         for(int i=0; i<len; i++) {
 6             int m = abs(nums[i])-1; // index start from 0
 7             nums[m] = nums[m]>0 ? -nums[m] : nums[m];
 8         }
 9         vector<int> res;
10         for(int i = 0; i<len; i++) {
11             if(nums[i] > 0) res.push_back(i+1);
12         }
13         return res;
14     }
15 };

 

posted @ 2018-03-18 19:01  还是说得清点吧  阅读(123)  评论(0编辑  收藏  举报