leetcode 448. Find All Numbers Disappeared in an Array -easy (重要)

题目链接:

https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/

题目描述:

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]

题目翻译:
题目要求:给出一个整形数组,长度为n,数组中的整数都在1~n之间,有些数出现一次,有些数出现两次,求出那些没出现的数的集合。

解决方案:
1.

Swap the array, make the a[i] become the (a[i]-1)-th elements in the array. 


Traverse the array, if a[i]!=i+1, add i+1 into the answer array.


参考:https://blog.csdn.net/zibingling777/article/details/79008604


class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> ans;
        int n=nums.size();
        for(int i=0;i<n;i++){
            int j=i;
            while(nums[j]!=nums[nums[j]-1]){
                swap(nums[j],nums[nums[j]-1]);
            }
        }
        for(int i=0;i<n;i++){
            if(nums[i]!=i+1)
                ans.push_back(i+1);    //向向量vector,ans后面依次退入元素。
            }
        return result;
    }
};

2 .时间复杂度为O(n),空间复杂度为O(n)的做法。定义一个长度为n的数组temp,全都初始化为0。然后遍历给出的数组,令temp[nums[i]-1]=-1。

最后遍历数组temp,那些值为0的数的位置加上1就是所要求的没有出现的数字。
class Solution {  
public:  
    vector<int> findDisappearedNumbers(vector<int>& nums) {  
        int l=nums.size();  
        vector<int> temp(l,0);  
        vector<int> result;  
        for(int i=0;i<l;i++){  
            temp[nums[i]-1]=-1;  
        }  
        for(int i=0;i<l;i++){  
            if(temp[i]==0)  
               result.push_back(i+1);  
        }  
        return result;  
    }  
}; 

3 .时间复杂度为O(n),空间复杂度为O(1)的做法。(符合题目要求的做法,没有使用多余空间)。遍历数组,索引为i,将nums[i]-1所在的位置的数置为负数。再次遍历数组,索引为index,对于每个数组值,如果为负数,就代表index+1这个数已经出现过了,如果为正数,代表没出现过,放到要返回的数组里面。

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> result;
        int n=nums.size();
        for(int i=0;i<n;i++){
           int m=abs(nums[i])-1;   //去掉abs()就不能运行,为什么呢
            nums[m]=nums[m]>0?-nums[m]:nums[m];  //这是什么意思??
        }
        for(int i=0;i<n;i++){
            if(nums[i]>0)
                result.push_back(i+1); 
            }
        return result;
    }
};

 3. 思路


posted @ 2018-04-09 19:28  月夜_1  阅读(146)  评论(0编辑  收藏  举报