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; }