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

 

posted @   Jimmy_Cheng  阅读(199)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?
点击右上角即可分享
微信分享提示