LeetCode 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]

题目标签:Array
  题目给了我们一个nums array,其中的数字 范围是从1到n,让我们找到没有出现过的数字。
  这道题目和 #442 基本思想一样,因为数字范围是 1到n,index 范围是 0 到n-1,建立一个数字 和 index 的1对1 映射。
  遍历数组,对于每一个num,去 index = num - 1 的位置,把映射的数字变为负数,标记num已经出现过。
  最后再次遍历数组,把正数的数字的index + 1 加入 List,因为所有负数的数字,代表了有出现过的数字去标记过。只有正数的数字,没有数字去标记。
 

Java Solution:

Runtime beats 81.65% 

完成日期:05/09/2017

关键词:Array

关键点:把num 和 nums[num - 1] 做1对1的映射

 1 public class Solution 
 2 {
 3     public List<Integer> findDisappearedNumbers(int[] nums) 
 4     {
 5         List<Integer> dis = new ArrayList<>();
 6         
 7         //    iterate nums array.
 8         for(int i=0; i<nums.length; i++)
 9         {
10             int index = Math.abs(nums[i]) - 1;    // the nums[i] may be negative. 
11             if(nums[index] > 0)    // mark corresponding number to negative if it is positive.
12                 nums[index] *= -1;
13             
14         }
15         //    iterate nums again to add i if nums[i] is positive.
16         for(int i=0; i<nums.length; i++)
17         {
18             if(nums[i] > 0)
19                 dis.add(i+1);
20         }
21             
22 
23         return dis;
24     }
25 }

参考资料:

www.cnblogs.com/grandyang/p/6222149.html

LeetCode 题目列表 - LeetCode Questions List

原文地址:https://www.cnblogs.com/jimmycheng/p/7566220.html