448. Find All Numbers Disappeared in an Array

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了448. Find All Numbers Disappeared in an Array相关的知识,希望对你有一定的参考价值。

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]

给定一个整数数组,其中1 ≤ a[i] ≤ n (n = 数组长度),一些元素出现两次,其他的出现一次。

寻找所有[1, n]中没有出现在数组中的元素。

可以不使用额外空间并在O(n)运行时间求解吗?你可以假设返回列表不算额外空间。

 思路:直接在原数组上遍历。如果出现过,将其本来应该在的位置设置为负值。最后遍历,为正的即为缺失值

 1     public List<Integer> findDisappearedNumbers(int[] nums) {
 2          List<Integer> result = new ArrayList<>();
 3         for (int i=0;i<nums.length;i++)
 4         {
 5             int val = Math.abs(nums[i]) - 1;
 6             if(nums[val] > 0) {
 7                 nums[val] = -nums[val];
 8             }
 9         }
10         for(int i = 0; i < nums.length; i++) {
11             if(nums[i] > 0) {
12                 result.add(i+1);
13             }
14         }
15         return result;       
16     }

 

以上是关于448. Find All Numbers Disappeared in an Array的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array