找出没有出现过的数

来源:互联网 发布:python串口编程实例 编辑:程序博客网 时间:2024/04/30 12:30

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的数组,内部的元素的大小在n之间。有些元素出现过一次,有些元素出现过两次。
找到所有的在这个数组中没有出现过的元素。
小要求:能不能不花费额外的内存空间,并且使她的时间复杂度使O(n).返回的结果集合不算在额外的空间内

解题思路:

题目要求不使用额外的内存 空间,并且时间复杂度为O(n)
那么首先就不能通过创建一个空的长度为n的数组来保存没有出现过的数
那这该怎么做呢?只能在当前数组上,让它自己保存没有出现过的数。
我们可以想到,由于数组长度为n,并且1<=nums[i]<=n,因此,(nums[i]-1)刚好可以做为数组的下标。为了记录数字是否出现过,我们可以把(nums[i]-1)的位置的数字置为相反数,也就是说nums[abs(nums[i]) - 1] = -abs(nums[abs(nums[i]) - 1]);
最后我们再循环遍历一次集合nums,如果有位置的数还是正数,就证明当前位置(index)对应的数字(index+1)是没有出现过的。

上代码:

public class Solution {    public List<Integer> findDisappearedNumbers(int[] nums) {        List<Integer> rst = new ArrayList<>();        int size = nums.length;        int targetIndex;        for (int i=0; i<size; i++){            targetIndex = Math.abs(nums[i]) - 1;// 取得当前数字对应的数组的下标            nums[targetIndex] = -Math.abs(nums[targetIndex]);// 做取反操作        }        for (int i=0; i<size; i++) {            if (nums[i] > 0){                rst.add(i + 1);            }        }        return rst;    }}
0 0
原创粉丝点击