【数组】448. 找到所有数组中消失的数字

题目:

 

 

解答:

方法一:哈希表。

方法二:原地修改。

(1)我们需要知道数组中存在的数字,由于数组的元素取值范围是 [1, N],所以我们可以不使用额外的空间去解决它。

(2)我们可以在输入数组本身以某种方式标记已访问过的数字,然后再找到缺失的数字。

算法:

(1)遍历输入数组的每个元素一次。

(2)我们将把 |nums[i]|-1 索引位置的元素标记为负数。即 nums[|nums[i] |- 1] ×−1 。

(3)然后遍历数组,若当前数组元素 nums[i] 为负数,说明我们在数组中存在数字 i+1

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) 
 4     {
 5          // Iterate over each of the elements in the original array
 6         for (int i = 0; i < nums.size(); i++) {
 7             
 8             // Treat the value as the new index
 9             int newIndex = std::abs(nums[i]) - 1;
10             
11             // Check the magnitude of value at this new index
12             // If the magnitude is positive, make it negative 
13             // thus indicating that the number nums[i] has 
14             // appeared or has been visited.
15             if (nums[newIndex] > 0) 
16             {
17                 nums[newIndex] *= -1;
18             }
19         }
20         
21         // Response array that would contain the missing numbers
22         vector<int> result;
23         
24         // Iterate over the numbers from 1 to N and add all those
25         // that have positive magnitude in the array
26         for (int i = 1; i <= nums.size(); i++) 
27         {
28             
29             if (nums[i - 1] > 0) 
30             {
31                 result.push_back(i);
32             }
33         }
34         
35         return result;
36     }
37 };

 

posted @ 2020-05-04 17:22  梦醒潇湘  阅读(283)  评论(0)    收藏  举报