码迷,mamicode.com
首页 > 移动开发 > 详细

448. Find All Numbers Disappeared in an Array

时间:2017-10-15 11:38:08      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:运行时间   length   elements   run   ext   other   arraylist   math   运行   

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

标签:运行时间   length   elements   run   ext   other   arraylist   math   运行   

原文地址:http://www.cnblogs.com/wzj4858/p/7669858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!