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.题目要求,输入一个大小为n的数组,数组中包含着值为1~n的元素,有的值出现过一次,有的值出现过两次,而咱们须要找到没有在数组中出现的1~n中的值,并以List形式返回这些值。
这道题额外要求了咱们须要在O(n)的时间复杂度下解决这个问题,同时不使用额外空间(返回的list不算作额外空间)数组Example:
Input:[4,3,2,7,8,2,3,1]
Output:[5,6]app
public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> res = new ArrayList<Integer>(); for(int num : nums){ int val = Math.abs(num)-1; if(nums[val] > 0){ nums[val] = - nums[val]; } } for(int i =0;i<nums.length;i++){ if(nums[i] > 0){ res.add(i+1); } } return res; }