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




1 要不要排序？ 如果要排序， 则线性运行时间的排序算法一定会消耗额外的存储空间。

2 曾尝试找相同元素，但该方法也不可行。

1 计数排序。

class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {

int[] counts = new int[nums.length];

for(int i=0; i<nums.length; i++) {
counts[nums[i]-1]++;
}

List<Integer> returnList = new ArrayList<Integer>();
for(int i=0; i<nums.length; i++) {
if(counts[i]==0) {
}
}

return returnList;
}
}

result:

second try:

class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {

for(int i=0; i<nums.length; i++) {
int val = Math.abs(nums[i]);
if(0<nums[val-1]) {
nums[val-1] = - nums[val-1];
}
}

List<Integer> returnList = new ArrayList<Integer>();
for(int i=0; i<nums.length; i++) {
if(0<nums[i]) {
}
}

return returnList;
}
}

result:

conclustion:

LeetCode中问你是否能找到一个空间复杂度。。的算法，一般是不做强制要求的。我觉得如果想检测提交算法的空间复杂度，还是能做到的。只是没有去做。

posted @ 2018-04-20 16:20  Zhao_Gang  阅读(70)  评论(0编辑  收藏  举报