448. Find All Numbers Disappeared in an Array【easy】
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]
解法一:
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 };
参考了大神的解法和解释:First iteration to negate values at position whose equal to values appear in array. Second iteration to collect all position whose value is positive, which are the missing values. Complexity is O(n) Time and O(1) space.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 :-)
假如我们给定的序列为[8,7,1,2,8,3,4,2],下面给出推导:
每行标记颜色的表示该次改变的值,黄色为第一次搞,即需要变为负值;绿色为非第一次搞,已经为负值了,就不要改变了。最后可以看到剩下为正数的下标就是我们的所求。
再解释一下为什么必须要abs(nums[i]),是因为题目中数组的长度就是n,而且最大值也是n为止,那么既少元素又要凑够n个数,里面必然是有重复的元素的,那么对于重复的元素我我们一开始置为了负值,如果不取abs的话,下次再来就会造成数组越界的。比如下面就是越界的例子:
解法二:
1 class Solution { 2 public List<Integer> findDisappearedNumbers(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 int n = nums.length; 5 for (int i = 0; i < nums.length; i ++) 6 { 7 nums[(nums[i]-1) % n] += n; 8 } 9 10 for (int i = 0; i < nums.length; i ++) 11 { 12 if (nums[i] <= n) res.add(i+1); 13 } 14 15 return res; 16 } 17 }
另外一位大神的解法:We can change back the value after find out result;How to do it?We can simply traverse array again and for each element, call nums[i] = nums[i] % n; to restore.