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]


题意:

给定一个整数数组a,其中数组元素满足1 ≤ a[i] ≤ n(n为数组的大小),a中有些元素出现多次,有些只出现一次。现在请写一个函数,找出数字[1,n]中没有在数组a中出现的 所有数字。

要求不能用多余的空间,另外要求在O(n)的时间复杂度内完成此题。


代码:

public class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        // int res[];
        // List<Integer> list=new ArrayList<Integer>(new Integer(13));
        // List res = new List();
        List<Integer> res= new ArrayList<Integer>();           #定义List类型的返回结果
        for(int i=0; i<n; i++){
            int index = Math.abs(nums[i])-1;      //元素num[i]对应num中的下标,元素num[i]可能被更改过,故加上绝对值,确保下标是正数
            nums[index] = -Math.abs(nums[index]);     //将元素num[i]对应的下标的元素变成负数
        }            

        for(int i=0; i<n; i++){     //统计num中对应的值没有变成负数的下标,这些下标即为没有在num中出现的数
            if(nums[i]>0){
                res.add(i+1);
            }
        }
        return res;
    }
}


笔记:

1、算法思想头一次接触,正负号标记法,参考了http://bookshadow.com/weblog/2016/11/01/leetcode-find-all-numbers-disappeared-in-an-array/

2、java的List集合类型,声明方法在网上找了大半天,参考了http://blog.csdn.net/friendan/article/details/17529683




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值