首页 > 学院 > 开发设计 > 正文

448.Find All Numbers Disappeared in an Array

2019-11-06 06:25:28
字体:
来源:转载
供稿:网友

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]

Subscribe to see which companies asked this question.

first answer(using two loop) wrong reason: time limit exceeded

class Solution {public: vector<int> findDisappearedNumbers(vector<int>& nums) { int s = nums.size(); vector<int> out; for (int i = 1; i <= s; i++) { out.push_back(i); } int in = 0; for (int j = 0; j < s; j++) { if (nums[j] == i) in++; } if (in == 0) { out.push_back(i); } return out; }};

correct answer:

class Solution {public: vector<int> findDisappearedNumbers(vector<int>& nums) { vector<int> out; int s = nums.size(); for(int i=0; i<s; i++) { int m = nums[i]-1; if(nums[m]>0){ nums[m]=-nums[m]; } else{ nums[m]=nums[m]; } } for(int i = 0; i<s; i++) { if(nums[i] > 0) out.push_back(i+1); } return out; }};

analyse: to avoid using extra space,use the sign symbol of position as the mark to existance.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表