448. Find All Numbers Disappeared in an Array

来源:互联网 发布:mac .git文件夹 编辑:程序博客网 时间:2024/05/16 00:44

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到n没有出现过的数字(这里n是数组长度),同时给了复杂度限制o(n)和空间限制no extra。

思路是让 nums[nums[i] - 1] 取反,再判断 nums[] 大于零的元素即可实现。为什么不是 nums[nums[i]] ?因为 nums[nums[i]] 有可能越界。

代码如下:

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> ret = new ArrayList<Integer>();        for (int i = 0; i < nums.length; i++) {            int val = Math.abs(nums[i]) - 1;            if (nums[val] > 0) {                nums[val] = -nums[val];            }        }        for (int j = 0; j < nums.length; j ++) {            if (nums[j] > 0) {                ret.add(j + 1);            }        }        return ret;    }}


0 0
原创粉丝点击