您的位置:首页 > 移动开发

leetcode_448. Find All Numbers Disappeared in an Array 找出不在数组中的数,正负号标记法

2016-12-20 22:24 204 查看
题目:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐