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]

分析

n位整数数组本应包含1~n所有数,实际缺少了其中一些,找出这些缺少的数。

限制条件:不占用额外空间(除返回的list以外),时间复杂度O(n)

解答

解法1:(我)把数组下标+1当做一个"新数组",出现的则将对应下标+1标记为负数,未标记的下标+1则是未出现的数(18ms)

遍历数组,遇到4则将数组中第4个数(下标为3)修改为负数

再次遍历数组,若第m个数(下标为m-1)没有被修改为负数,意味着m是数组中缺少的数

例:

1   2   3   4   5   6   7   8  (下标+1)

4   3   2   7   8   2   3   1

-4 -3  -2  -7  8   2  -3  -1

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++){
            nums[Math.abs(nums[i])-1] = - Math.abs(nums[Math.abs(nums[i])-1]);
            //最内部绝对值:遍历到已被标记为负数的数时,要用其绝对值来寻找下标
            //最外部绝对值:重复出现的数,下标已被标记过一次,再直接求相反数会又变为正,需先绝对值再求相反数
        }
        for (int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                list.add(i + 1);
            }
        }
        return list;
    }
}


解法2:解法1中的第5行拆开写(17ms√)

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++){
            int index = Math.abs(nums[i])-1;
            if(nums[index] > 0)
                nums[index] = - nums[index];
        }
        for (int i = 0; i < nums.length; i++){
            if(nums[i] > 0){
                list.add(i + 1);
            }
        }
        return list;
    }
}
posted @ 2017-02-18 10:35  妙音天女  阅读(191)  评论(0编辑  收藏  举报