博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode | 448. Find All Numbers Disappeared in an Array【经典题】
阅读量:3572 次
发布时间:2019-05-20

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

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]


我自己做的相当笨的方法,遍历套遍历,非常笨。代码如下:

public class Solution {
public List
findDisappearedNumbers(int[] nums) { Arrays.sort(nums); List
list = new ArrayList
(); int flag = 0; for(int i = 1; i <= nums.length; i++) { while(true) { if(i == nums[flag]) { if(flag < nums.length - 1) flag++; break; } if(i < nums[flag] || i > nums[nums.length - 1]) { list.add(i); break; } flag++; } } return list; }}

看到discuss里面的又跪了,简单解释下:

思路是这样的,数组的每个位置经历一次正负号的标记,标记后,如果该位置的值仍是正数,则说明其未被标记过,即该位置下标+1的对应数在数组中不曾出现。
标记的方法是遍历原数组中的每个值,每个值-1后,代表的是1到n排序后的下标,把对应下标上的数组值置为负数,证明其出现过。否则没有。

public List
findDisappearedNumbers(int[] nums) { List
ret = new ArrayList
(); for(int i = 0; i < nums.length; i++) { int val = Math.abs(nums[i]) - 1; if(nums[val] > 0) { nums[val] = -nums[val]; } } for(int i = 0; i < nums.length; i++) { if(nums[i] > 0) { ret.add(i+1); } } return ret;}

转载地址:http://aijgj.baihongyu.com/

你可能感兴趣的文章
nowcoder 左神算法1
查看>>
code刷题
查看>>
学习日记03
查看>>
学习日记04
查看>>
js自定义数据顺序进行升序或者降序排序
查看>>
【零】简单数仓框架优化、配置及基准测试
查看>>
Sqoop的安装及测试
查看>>
Kylin的简单使用
查看>>
Presto的概念和安装使用
查看>>
Druid的Web页面使用
查看>>
Scala-HelloWorld
查看>>
Scala-IDEA中环境部署
查看>>
Scala-HelloWorld解析
查看>>
Scala-变量和数据类型
查看>>
Scala-流程控制
查看>>
iOS蓝牙原生封装,助力智能硬件开发
查看>>
iOS 代码的Taste(品位)
查看>>
iOS开发代码规范
查看>>
iOS组件化实践(基于CocoaPods)
查看>>
数据结构之栈
查看>>