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]

原题地址: Find All Numbers Disappeared in an Array

难度: Easy

题意: 给出n个数,范围在[1, n]之间,数组中存在重复,返回1-n之中缺少的数,要求不用额外的空间,时间复杂度为O(n)

不用额外的空间,只能用数组进行计数

(1)遍历数组,用索引进行计数,出现一次将索引值变为负数.数值[1, n]对应的索引为[0, n-1]比如上个例子中4,索引值为3,所以将数值7变为-7

(2)遍历一次之后,重复一次的值的索引对应的值为正数,而其他数都为负数, 再遍历一次,找出值为正数的索引值

代码:

class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
res = []
for i in range(n):
idx = abs(nums[i]) - 1 # 索引值
nums[idx] = -abs(nums[idx]) for i in range(n):
if nums[i] > 0:
res.append(i+1)
return res

时间复杂度:O(n)

空间复杂度:O(1)

最新文章

  1. MFC获取Windows启动状态(正常启动、安全模式启动、网络安全模式启动)
  2. C# 数据库查询总结
  3. Flink - RocksDBStateBackend
  4. mysqli报错(HY000/2002)
  5. chrome常用插件
  6. Android 迷之Version管理
  7. About abstract class.
  8. cocos2d-x游戏开发系列教程-坦克大战游戏之虚拟手柄的显示
  9. python demo整理
  10. Realsense Camera SDK 开发手记(一)
  11. ES6之"let"能替代"var"吗?
  12. 如何一条sql语句查找表中第二大值
  13. bzoj 3751: [NOIP2014]解方程
  14. Clion设置字体大小和护眼色
  15. 细说java系列之注解
  16. 【GMT43智能液晶模块】例程六:WWDG看门狗实验——复位ARM
  17. Unity3D Update() 和 FixedUpdate()区别
  18. 20155209 林虹宇Exp2 后门原理与实践
  19. C# 常用控件属性及方法介绍
  20. Oracle常用方法

热门文章

  1. LuoguP3964 [TJOI2013]松鼠聚会【切比雪夫距离/前缀和】
  2. 关于asp.net网址出现乱码问题的解决方法
  3. 因磁盘空间不足导致HDFS的NameNode进入安全模式问题记录
  4. vue中的问题思考
  5. django 相关问题
  6. (027)[技术资料]业余制作Windows图标
  7. CZ-python01-06
  8. HBase文档操作--练习篇
  9. Camera和 tris,verts的优化
  10. Windows下Apache应用环境塔建安全设置(目录权限设置)