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

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

题目链接:

https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/

题目描述:

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.

Swap the array, make the a[i] become the (a[i]-1)-th elements in the array. 

 

Traverse the array, if a[i]!=i+1, add i+1 into the answer array.

 

参考:https://blog.csdn.net/zibingling777/article/details/79008604

 
class Solution {public:    vector
findDisappearedNumbers(vector
& nums) { vector
ans; int n=nums.size(); for(int i=0;i
 

2 .时间复杂度为O(n),空间复杂度为O(n)的做法。定义一个长度为n的数组temp,全都初始化为0。然后遍历给出的数组,令temp[nums[i]-1]=-1。

最后遍历数组temp,那些值为0的数的位置加上1就是所要求的没有出现的数字。
class Solution {  public:      vector
findDisappearedNumbers(vector
& nums) { int l=nums.size(); vector
temp(l,0); vector
result; for(int i=0;i

3 .时间复杂度为O(n),空间复杂度为O(1)的做法。(符合题目要求的做法,没有使用多余空间)。遍历数组,索引为i,将nums[i]-1所在的位置的数置为负数。再次遍历数组,索引为index,对于每个数组值,如果为负数,就代表index+1这个数已经出现过了,如果为正数,代表没出现过,放到要返回的数组里面。

class Solution {public:    vector
findDisappearedNumbers(vector
& nums) { vector
result; int n=nums.size(); for(int i=0;i
0?-nums[m]:nums[m]; //这是什么意思?? } for(int i=0;i
0) result.push_back(i+1); } return result; }};

 3. 思路

 

转载于:https://www.cnblogs.com/zb-ml/p/8762284.html

你可能感兴趣的文章
文件上传---动作条
查看>>
自制CA签发证书
查看>>
解决mysql “too many connections”
查看>>
梳理下MySQL崩溃恢复过程
查看>>
红包金额均分实现
查看>>
Google校园招聘题 -- 程序员买房
查看>>
线程的属性(优先级、守护线程、未捕获异常处理器)
查看>>
oracle批量插入测试数据
查看>>
goahead-3.6.2-src 移植到linux
查看>>
Mysql数据库调优和性能优化的21条最佳实践
查看>>
iOS视频播放-MPMoviePlayerController
查看>>
mysql导入导出数据中文乱码解决方法小结
查看>>
使用Mob短信sdk遇到的问题,解决
查看>>
android-------- 强引用、软引用、弱引用、虚引用使用
查看>>
HTML标签marquee实现滚动效果
查看>>
html字符操作
查看>>
oracle函数
查看>>
百度贴吧爬虫1.0
查看>>
ant+jmeter接口批量执行测试用例
查看>>
Mongodb
查看>>