LeetCode--448. Find All Numbers Disappeared in an Array

来源:互联网 发布:玻璃厂加工中心编程 编辑:程序博客网 时间:2024/06/04 18:32

448. 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]
意思就是给一个长度为n的数组,数组里的元素都≥1,≤n,就是1 ≤ a[i] ≤ n (n = size of array),[1,n]中的有些数字可能不在数组中出现,找出哪些数字没有出现。

代码如下:

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> test;   //用于找出[1,n]中哪些数字没有出现        vector<int> ans;    //将没有出现的数字放入ans        for(int i=0;i<=nums.size();i++){    //将test置零,且test的长度为n+1,注意i要<=nums.size(),不能只<            test.push_back(0);        }        for(int i=0;i<nums.size();i++){            if(!test[nums[i]]){                test[nums[i]]++;            }        }        for(int i=1;i<=nums.size();i++){  //同样注意i要<=nums.size(),不能只<,且i从1开始遍历,因为原数组不包含0            if(!test[i]){                ans.push_back(i);            }        }        return ans;    }};

用时142ms,击败了59.57%的c++程序。
我在关于这题的讨论里看到了一种更好的解法,时间复杂度为O(n),空间复杂度为O(1),代码如下:

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        int len = nums.size();        for(int i=0; i<len; i++) {            int m = abs(nums[i])-1; // index start from 0            nums[m] = nums[m]>0 ? -nums[m] : nums[m];        }        vector<int> res;        for(int i = 0; i<len; i++) {            if(nums[i] > 0) res.push_back(i+1);        }        return res;    }};

含义就是如果如果[1,n]之间某一个数字出现了,就将nums[i-1]=-nums[i-1],将nums[i-1]变成负数用来说明i出现了,处理完之后,再遍历一遍nums,如果nums[i]为正,则就说明i+1未出现。

原作者的解释:

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.

                                             
0 0
原创粉丝点击