码迷,mamicode.com
首页 > 移动开发 > 详细

448. Find All Numbers Disappeared in an Array

时间:2017-04-04 09:25:17      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:class   strong   hang   push   oid   tput   overflow   equal   others   

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]

 

idea: It‘s hard to solve without extra space and in O(n) without the condition  1 ≤ a[i] ≤ n. 

Solution 1: for the number a[a[i]-1], if it is positive, assign it to its opposite number, else unchange it. The logic is if i+1 appear in the array, a[i] will be negative, so if a[i] is positive, i+1 doesn‘t appear in the array.

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

Solution 2: move nums[i] from positon i to its right position nums[i]-1, swap nums[i] and nums[nums[i]-1]. Finally, if i doesn‘t equal nums[i]-1, means i+1 doesn‘t appear in the array. Note the line 6-8

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4         vector<int> res;
 5         for (int i=0;i<nums.size();i++){
 6             if (nums[i]!=nums[nums[i]-1]){
 7                 swap(nums[i],nums[nums[i]-1]);
 8                 --i;
 9             }
10         }
11         for (int i=0;i<nums.size();i++){
12             if (i!=nums[i]-1){
13                 res.push_back(i+1);
14             }
15         }
16         return res;
17     }
18 };

Solution 3: add nums[nums[i]-1] to n, use (nums[i]-1)%n to avoid the overflow of nums[i]-1. Finally, if nums[i]<=n, i+1 is the disappeard number.

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4         vector<int> res;
 5         int size=nums.size();
 6         for (int i=0;i<size;i++){
 7             nums[(nums[i]-1)%size]+=size; //mod to avoid overflow
 8         }
 9         for (int i=0;i<size;i++){
10             if (nums[i]<=size){
11                 res.push_back(i+1);
12             }
13         }
14         return res;
15     }
16 };

 

448. Find All Numbers Disappeared in an Array

标签:class   strong   hang   push   oid   tput   overflow   equal   others   

原文地址:http://www.cnblogs.com/anghostcici/p/6664283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!