448.Find All Numbers Disappeared in an Array
来源:互联网 发布:成都管家婆软件代理 编辑:程序博客网 时间:2024/06/07 06:25
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.
0 0
- LeetCode-Array-448. Find All Numbers Disappeared in an Array
- [LC][Array] 448. Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- Find All Numbers Disappeared in an Array
- 448. Find All Numbers Disappeared in an Array
- 448. Find All Numbers Disappeared in an Array
- 448. Find All Numbers Disappeared in an Array
- leetcode:448. Find All Numbers Disappeared in an Array
- 树状数组学习心得
- BZOJ1029: [JSOI2007]建筑抢修
- 单例模式(Singleton-Pattern)
- 本机idea远程调试flume
- 深度学习(16):Induction
- 448.Find All Numbers Disappeared in an Array
- 内聚耦合分类
- linux date 命令详解
- win7下DOS命令无法使用的解决办法
- opencv3.2+opencv_contrib+cmake
- HTTP协议详解
- 深度学习(17):无人机
- 基于Java语言的安卓程序编写之七TextView控件
- Hibernate框架学习(一)