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]

链接:https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/#/description

3/25/2017

performance 14% 35ms

 1 public class Solution {
 2     public List<Integer> findDisappearedNumbers(int[] nums) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         if (nums.length == 0) return ret;
 5 
 6         for (int i = 0; i < nums.length; i++) {
 7             ret.add(0);
 8         }
 9         for (int i = 0; i < nums.length; i++) {
10             ret.set(nums[i] - 1, ret.get(nums[i] - 1) + 1);
11         }
12         int index = 0;
13         for (int i = 0; i < nums.length; i++) {
14             if (ret.get(i) == 0) {
15                 ret.set(index, i + 1);
16                 index++;
17             }
18         }
19         return ret.subList(0, index);
20     }
21 }

别人的方法

https://discuss.leetcode.com/topic/65738/java-accepted-simple-solution/3

更多讨论:https://discuss.leetcode.com/category/575/find-all-numbers-disappeared-in-an-array

原文地址:https://www.cnblogs.com/panini/p/6622304.html