博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
448. Find All Numbers Disappeared in an Array
阅读量:4692 次
发布时间:2019-06-09

本文共 1872 字,大约阅读时间需要 6 分钟。

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]

 

idea: It's hard to solve without extra space and in O(n) without the condition  1 ≤ a[i] ≤ n. 

Solution 1: for the number a[a[i]-1], if it is positive, assign it to its opposite number, else unchange it. The logic is if i+1 appear in the array, a[i] will be negative, so if a[i] is positive, i+1 doesn't appear in the array.

1 class Solution { 2 public: 3     vector
findDisappearedNumbers(vector
& nums) { 4 vector
res; 5 for (int i=0;i
0)?(-nums[idx]):nums[idx]; 8 } 9 for (int i=0;i
0) res.push_back(i+1);11 }12 return res;13 }14 };

Solution 2: move nums[i] from positon i to its right position nums[i]-1, swap nums[i] and nums[nums[i]-1]. Finally, if i doesn't equal nums[i]-1, means i+1 doesn't appear in the array. Note the line 6-8

1 class Solution { 2 public: 3     vector
findDisappearedNumbers(vector
& nums) { 4 vector
res; 5 for (int i=0;i

Solution 3: add nums[nums[i]-1] to n, use (nums[i]-1)%n to avoid the overflow of nums[i]-1. Finally, if nums[i]<=n, i+1 is the disappeard number.

1 class Solution { 2 public: 3     vector
findDisappearedNumbers(vector
& nums) { 4 vector
res; 5 int size=nums.size(); 6 for (int i=0;i

 

转载于:https://www.cnblogs.com/anghostcici/p/6664283.html

你可能感兴趣的文章
初级ant的学习
查看>>
redis数据结构--String
查看>>
POJ 3279 Fliptile (二进制枚举)
查看>>
memcached 细究(三)
查看>>
future
查看>>
关于main函数传参数的问题
查看>>
getTickCount()函数 VS GetTickCount()函数
查看>>
嵌入式jetty
查看>>
2017~回顾分享
查看>>
使用svn——项目的目录布局
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>