LeetCode——Find All Numbers Disappeared in an Array

Question

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]

Solution

用hash table求解。

Answer

class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
map<int, int> dict;
for (int i : nums)
dict[i]++;
vector<int> res;
for (int i = 1; i <= nums.size(); i++)
if (dict[i] == 0)
res.push_back(i);
return res;
}
};

时间复杂度O(2n)。 网上给出了另外一种解答:

The idea is very similar to problem 442. Find All Duplicates in an Array: https://leetcode.com/problems/find-all-duplicates-in-an-array/.

First iteration to negate values at position whose equal to values appear in array. Second iteration to collect all position whose value is positive, which are the missing values. Complexity is O(n) Time and O(1) space.

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. Android 捕获异常并在应用崩溃后重启应用
  2. 《HTML5》 Audio/Video全解
  3. 分组统计并计算每组数量sql
  4. Android 回调接口是啥,回调机制详解(zhuan)
  5. Android 三大图片加载框架的对比——ImageLoader,Picasso,Glide
  6. C# Socket简单例子(服务器与客户端通信)
  7. Ubuntu 15.10 x64 安装 Android SDK
  8. php5.2 连接 SQL Server2008
  9. 分批次获取git for windows的源代码
  10. delphi xe5 android 开发数据访问手机端(二)
  11. Java的内存机制详解
  12. DES加密例子
  13. [CSDN_Markdown] Markdown基本语法
  14. Java并发之Condition
  15. MYSQL 查看最大连接数和修改最大连接数
  16. MFC树形控件的使用(右键点击)
  17. java_生态环境
  18. R语言-画柱形图
  19. 爬虫从网页中去取的数据中包含&amp;nbsp;空格
  20. DokuWiki

热门文章

  1. 68、 FragmentPagerAdapter+ViewPager实现Tab
  2. Win10下Hyper-V设置网络连接
  3. hdu3535(AreYouBusy)
  4. 第15章—数据库连接池(DBCP2)
  5. 标准编译安装(cmake make)
  6. 利用VMware克隆linux虚拟机需要注意的事项
  7. mysql 建立表之间关系 练习 2
  8. BFC(Block Formatting Context)基础分析
  9. path的join和resolve的使用区别
  10. network FAQ